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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,112 +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 evals = require('@mastra/core/evals');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
10
11
  var Cloudflare__default = /*#__PURE__*/_interopDefault(Cloudflare);
11
12
 
12
13
  // src/storage/index.ts
13
- var LegacyEvalsStorageCloudflare = class extends storage.LegacyEvalsStorage {
14
- operations;
15
- constructor({ operations }) {
16
- super();
17
- this.operations = operations;
18
- }
19
- async getEvalsByAgentName(agentName, type) {
20
- try {
21
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
22
- const keyObjs = await this.operations.listKV(storage.TABLE_EVALS, { prefix: `${prefix}${storage.TABLE_EVALS}` });
23
- const evals = [];
24
- for (const { name: key } of keyObjs) {
25
- const data = await this.operations.getKV(storage.TABLE_EVALS, key);
26
- if (!data) continue;
27
- if (data.agent_name !== agentName) continue;
28
- if (type) {
29
- const isTest = data.test_info !== null && data.test_info !== void 0;
30
- const evalType = isTest ? "test" : "live";
31
- if (evalType !== type) continue;
32
- }
33
- const mappedData = {
34
- ...data,
35
- runId: data.run_id,
36
- testInfo: data.test_info
37
- };
38
- evals.push(mappedData);
39
- }
40
- evals.sort((a, b) => {
41
- const aTime = new Date(a.createdAt || 0).getTime();
42
- const bTime = new Date(b.createdAt || 0).getTime();
43
- return bTime - aTime;
44
- });
45
- return evals;
46
- } catch (error$1) {
47
- throw new error.MastraError(
48
- {
49
- id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
50
- domain: error.ErrorDomain.STORAGE,
51
- category: error.ErrorCategory.THIRD_PARTY,
52
- text: "Failed to get evals by agent name"
53
- },
54
- error$1
55
- );
56
- }
57
- }
58
- async getEvals(options) {
59
- try {
60
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
61
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
62
- const keyObjs = await this.operations.listKV(storage.TABLE_EVALS, { prefix: `${prefix}${storage.TABLE_EVALS}` });
63
- const evals = [];
64
- for (const { name: key } of keyObjs) {
65
- const data = await this.operations.getKV(storage.TABLE_EVALS, key);
66
- if (!data) continue;
67
- if (agentName && data.agent_name !== agentName) continue;
68
- if (type) {
69
- const isTest = data.test_info !== null && data.test_info !== void 0;
70
- const evalType = isTest ? "test" : "live";
71
- if (evalType !== type) continue;
72
- }
73
- if (dateRange?.start || dateRange?.end) {
74
- const evalDate = new Date(data.createdAt || data.created_at || 0);
75
- if (dateRange.start && evalDate < dateRange.start) continue;
76
- if (dateRange.end && evalDate > dateRange.end) continue;
77
- }
78
- const mappedData = {
79
- ...data,
80
- runId: data.run_id,
81
- testInfo: data.test_info
82
- };
83
- evals.push(mappedData);
84
- }
85
- evals.sort((a, b) => {
86
- const aTime = new Date(a.createdAt || 0).getTime();
87
- const bTime = new Date(b.createdAt || 0).getTime();
88
- return bTime - aTime;
89
- });
90
- const start = page * perPage;
91
- const end = start + perPage;
92
- const paginatedEvals = evals.slice(start, end);
93
- return {
94
- page,
95
- perPage,
96
- total: evals.length,
97
- hasMore: start + perPage < evals.length,
98
- evals: paginatedEvals
99
- };
100
- } catch (error$1) {
101
- throw new error.MastraError(
102
- {
103
- id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
104
- domain: error.ErrorDomain.STORAGE,
105
- category: error.ErrorCategory.THIRD_PARTY,
106
- text: "Failed to get evals"
107
- },
108
- error$1
109
- );
110
- }
111
- }
112
- };
113
14
  var MemoryStorageCloudflare = class extends storage.MemoryStorage {
114
15
  operations;
115
16
  constructor({ operations }) {
@@ -120,6 +21,17 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
120
21
  if (!metadata) return void 0;
121
22
  return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
122
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
+ }
123
35
  async getThreadById({ threadId }) {
124
36
  const thread = await this.operations.load({ tableName: storage.TABLE_THREADS, keys: { id: threadId } });
125
37
  if (!thread) return null;
@@ -147,61 +59,23 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
147
59
  return null;
148
60
  }
149
61
  }
150
- async getThreadsByResourceId({ resourceId }) {
62
+ async listThreadsByResourceId(args) {
151
63
  try {
152
- const keyList = await this.operations.listKV(storage.TABLE_THREADS);
153
- const threads = await Promise.all(
154
- keyList.map(async (keyObj) => {
155
- try {
156
- const data = await this.operations.getKV(storage.TABLE_THREADS, keyObj.name);
157
- if (!data) return null;
158
- const thread = typeof data === "string" ? JSON.parse(data) : data;
159
- if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
160
- return {
161
- ...thread,
162
- createdAt: storage.ensureDate(thread.createdAt),
163
- updatedAt: storage.ensureDate(thread.updatedAt),
164
- metadata: this.ensureMetadata(thread.metadata)
165
- };
166
- } catch (error$1) {
167
- const mastraError = new error.MastraError(
168
- {
169
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
170
- domain: error.ErrorDomain.STORAGE,
171
- category: error.ErrorCategory.THIRD_PARTY,
172
- details: {
173
- resourceId
174
- }
175
- },
176
- error$1
177
- );
178
- this.logger?.trackException(mastraError);
179
- this.logger?.error(mastraError.toString());
180
- return null;
181
- }
182
- })
183
- );
184
- return threads.filter((thread) => thread !== null);
185
- } catch (error$1) {
186
- const mastraError = new error.MastraError(
187
- {
188
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
189
- domain: error.ErrorDomain.STORAGE,
190
- category: error.ErrorCategory.THIRD_PARTY,
191
- details: {
192
- resourceId
193
- }
194
- },
195
- error$1
196
- );
197
- this.logger?.trackException(mastraError);
198
- this.logger?.error(mastraError.toString());
199
- return [];
200
- }
201
- }
202
- async getThreadsByResourceIdPaginated(args) {
203
- try {
204
- 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);
205
79
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
206
80
  const keyObjs = await this.operations.listKV(storage.TABLE_THREADS, { prefix: `${prefix}${storage.TABLE_THREADS}` });
207
81
  const threads = [];
@@ -212,24 +86,23 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
212
86
  threads.push(data);
213
87
  }
214
88
  threads.sort((a, b) => {
215
- const aTime = new Date(a.createdAt || 0).getTime();
216
- const bTime = new Date(b.createdAt || 0).getTime();
217
- 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;
218
92
  });
219
- const start = page * perPage;
220
- const end = start + perPage;
221
- const paginatedThreads = threads.slice(start, end);
93
+ const end = perPageInput === false ? threads.length : offset + perPage;
94
+ const paginatedThreads = threads.slice(offset, end);
222
95
  return {
223
96
  page,
224
- perPage,
97
+ perPage: perPageForResponse,
225
98
  total: threads.length,
226
- hasMore: start + perPage < threads.length,
99
+ hasMore: perPageInput === false ? false : offset + perPage < threads.length,
227
100
  threads: paginatedThreads
228
101
  };
229
102
  } catch (error$1) {
230
103
  throw new error.MastraError(
231
104
  {
232
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
105
+ id: "CLOUDFLARE_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
233
106
  domain: error.ErrorDomain.STORAGE,
234
107
  category: error.ErrorCategory.THIRD_PARTY,
235
108
  text: "Failed to get threads by resource ID with pagination"
@@ -297,7 +170,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
297
170
  return this.operations.getKey(storage.TABLE_MESSAGES, { threadId, id: messageId });
298
171
  } catch (error) {
299
172
  const message = error instanceof Error ? error.message : String(error);
300
- 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 });
301
174
  throw error;
302
175
  }
303
176
  }
@@ -306,7 +179,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
306
179
  return this.operations.getKey(storage.TABLE_MESSAGES, { threadId, id: "messages" });
307
180
  } catch (error) {
308
181
  const message = error instanceof Error ? error.message : String(error);
309
- 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 });
310
183
  throw error;
311
184
  }
312
185
  }
@@ -396,7 +269,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
396
269
  });
397
270
  } catch (error) {
398
271
  const message = error instanceof Error ? error.message : String(error);
399
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
272
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
400
273
  throw error;
401
274
  } finally {
402
275
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -414,7 +287,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
414
287
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
415
288
  return Array.isArray(arr) ? arr : [];
416
289
  } catch (e) {
417
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
290
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
418
291
  return [];
419
292
  }
420
293
  }
@@ -445,8 +318,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
445
318
  }
446
319
  }
447
320
  async saveMessages(args) {
448
- const { messages, format = "v1" } = args;
449
- if (!Array.isArray(messages) || messages.length === 0) return [];
321
+ const { messages } = args;
322
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
450
323
  try {
451
324
  const validatedMessages = messages.map((message, index) => {
452
325
  const errors = [];
@@ -469,9 +342,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
469
342
  const messageMigrationTasks = [];
470
343
  for (const message of validatedMessages) {
471
344
  const existingMessage = await this.findMessageInAnyThread(message.id);
472
- console.log(`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
+ );
473
348
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
474
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
349
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
475
350
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
476
351
  }
477
352
  }
@@ -500,10 +375,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
500
375
  ...cleanMessage,
501
376
  createdAt: storage.serializeDate(cleanMessage.createdAt)
502
377
  };
503
- console.log(`Saving message ${message.id} with content:`, {
504
- content: serializedMessage.content,
505
- contentType: typeof serializedMessage.content,
506
- isArray: Array.isArray(serializedMessage.content)
378
+ this.logger?.debug(`Saving message ${message.id}`, {
379
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
507
380
  });
508
381
  await this.operations.putKV({ tableName: storage.TABLE_MESSAGES, key, value: serializedMessage });
509
382
  })
@@ -539,8 +412,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
539
412
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
540
413
  );
541
414
  const list = new agent.MessageList().add(prepared, "memory");
542
- if (format === `v2`) return list.get.all.v2();
543
- return list.get.all.v1();
415
+ return { messages: list.get.all.db() };
544
416
  } catch (error$1) {
545
417
  throw new error.MastraError(
546
418
  {
@@ -603,7 +475,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
603
475
  const latestIds = await this.getLastN(threadMessagesKey, limit);
604
476
  latestIds.forEach((id) => messageIds.add(id));
605
477
  } catch {
606
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
478
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
607
479
  }
608
480
  }
609
481
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -634,111 +506,21 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
634
506
  const data = await this.operations.getKV(storage.TABLE_MESSAGES, key);
635
507
  if (!data) return null;
636
508
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
637
- console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
638
- content: parsed.content,
639
- contentType: typeof parsed.content,
640
- isArray: Array.isArray(parsed.content)
509
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
510
+ contentSummary: this.summarizeMessageContent(parsed.content)
641
511
  });
642
512
  return parsed;
643
513
  } catch (error) {
644
514
  const message = error instanceof Error ? error.message : String(error);
645
- this.logger.error(`Error retrieving message ${id}:`, { message });
515
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
646
516
  return null;
647
517
  }
648
518
  })
649
519
  );
650
520
  return messages.filter((msg) => msg !== null);
651
521
  }
652
- async getMessages({
653
- threadId,
654
- resourceId,
655
- selectBy,
656
- format
657
- }) {
658
- console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
659
- const actualFormat = format || "v1";
660
- console.log(`Using format: ${actualFormat}`);
661
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
662
- const messageIds = /* @__PURE__ */ new Set();
663
- if (limit === 0 && !selectBy?.include?.length) return [];
664
- try {
665
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
666
- await Promise.all([
667
- selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
668
- limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
669
- ]);
670
- const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
671
- const messages = await this.fetchAndParseMessagesFromMultipleThreads(
672
- Array.from(messageIds),
673
- selectBy?.include,
674
- targetThreadId
675
- );
676
- if (!messages.length) return [];
677
- try {
678
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
679
- const messageOrder = await this.getFullOrder(threadMessagesKey);
680
- const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
681
- messages.sort((a, b) => {
682
- const indexA = orderMap.get(a.id);
683
- const indexB = orderMap.get(b.id);
684
- if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
685
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
686
- });
687
- } catch (error$1) {
688
- const mastraError = new error.MastraError(
689
- {
690
- id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
691
- domain: error.ErrorDomain.STORAGE,
692
- category: error.ErrorCategory.THIRD_PARTY,
693
- text: `Error sorting messages for thread ${threadId} falling back to creation time`,
694
- details: {
695
- threadId
696
- }
697
- },
698
- error$1
699
- );
700
- this.logger?.trackException(mastraError);
701
- this.logger?.error(mastraError.toString());
702
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
703
- }
704
- const prepared = messages.map(({ _index, ...message }) => ({
705
- ...message,
706
- type: message.type === `v2` ? void 0 : message.type,
707
- createdAt: storage.ensureDate(message.createdAt)
708
- }));
709
- if (actualFormat === `v1`) {
710
- console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
711
- return prepared.map((msg) => ({
712
- ...msg,
713
- createdAt: new Date(msg.createdAt)
714
- }));
715
- }
716
- const list = new agent.MessageList({ threadId, resourceId }).add(prepared, "memory");
717
- return list.get.all.v2();
718
- } catch (error$1) {
719
- const mastraError = new error.MastraError(
720
- {
721
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
722
- domain: error.ErrorDomain.STORAGE,
723
- category: error.ErrorCategory.THIRD_PARTY,
724
- text: `Error retrieving messages for thread ${threadId}`,
725
- details: {
726
- threadId,
727
- resourceId: resourceId ?? ""
728
- }
729
- },
730
- error$1
731
- );
732
- this.logger?.trackException(mastraError);
733
- this.logger?.error(mastraError.toString());
734
- return [];
735
- }
736
- }
737
- async getMessagesById({
738
- messageIds,
739
- format
740
- }) {
741
- if (messageIds.length === 0) return [];
522
+ async listMessagesById({ messageIds }) {
523
+ if (messageIds.length === 0) return { messages: [] };
742
524
  try {
743
525
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
744
526
  (result) => !!result
@@ -749,12 +531,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
749
531
  createdAt: storage.ensureDate(message.createdAt)
750
532
  }));
751
533
  const list = new agent.MessageList().add(prepared, "memory");
752
- if (format === `v1`) return list.get.all.v1();
753
- return list.get.all.v2();
534
+ return { messages: list.get.all.db() };
754
535
  } catch (error$1) {
755
536
  const mastraError = new error.MastraError(
756
537
  {
757
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
538
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_BY_ID_FAILED",
758
539
  domain: error.ErrorDomain.STORAGE,
759
540
  category: error.ErrorCategory.THIRD_PARTY,
760
541
  text: `Error retrieving messages by ID`,
@@ -766,42 +547,202 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
766
547
  );
767
548
  this.logger?.trackException(mastraError);
768
549
  this.logger?.error(mastraError.toString());
769
- return [];
550
+ return { messages: [] };
770
551
  }
771
552
  }
772
- async getMessagesPaginated(args) {
773
- const { threadId, resourceId, selectBy, format = "v1" } = args;
774
- 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);
775
568
  try {
776
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
777
- 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
+ );
778
619
  let filteredMessages = messages;
779
- if (selectBy?.pagination?.dateRange) {
780
- const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
781
- filteredMessages = messages.filter((message) => {
782
- const messageDate = new Date(message.createdAt);
783
- if (dateStart && messageDate < dateStart) return false;
784
- 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;
785
629
  return true;
786
630
  });
787
631
  }
788
- const start = page * perPage;
789
- const end = start + perPage;
790
- 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
+ }
791
732
  return {
733
+ messages: finalMessages,
734
+ total,
792
735
  page,
793
- perPage,
794
- total: filteredMessages.length,
795
- hasMore: start + perPage < filteredMessages.length,
796
- messages: paginatedMessages
736
+ perPage: perPageForResponse,
737
+ hasMore
797
738
  };
798
739
  } catch (error$1) {
799
740
  const mastraError = new error.MastraError(
800
741
  {
801
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
742
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_FAILED",
802
743
  domain: error.ErrorDomain.STORAGE,
803
744
  category: error.ErrorCategory.THIRD_PARTY,
804
- 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)}`,
805
746
  details: {
806
747
  threadId,
807
748
  resourceId: resourceId ?? ""
@@ -809,9 +750,15 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
809
750
  },
810
751
  error$1
811
752
  );
812
- this.logger?.trackException?.(mastraError);
813
753
  this.logger?.error?.(mastraError.toString());
814
- 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
+ };
815
762
  }
816
763
  }
817
764
  async updateMessages(args) {
@@ -1097,10 +1044,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1097
1044
  case storage.TABLE_TRACES:
1098
1045
  if (!record.id) throw new Error("Trace ID is required");
1099
1046
  return `${prefix}${tableName}:${record.id}`;
1100
- case storage.TABLE_EVALS:
1101
- const evalId = record.id || record.run_id;
1102
- if (!evalId) throw new Error("Eval ID or run_id is required");
1103
- return `${prefix}${tableName}:${evalId}`;
1104
1047
  case storage.TABLE_SCORERS:
1105
1048
  if (!record.id) throw new Error("Score ID is required");
1106
1049
  return `${prefix}${tableName}:${record.id}`;
@@ -1340,11 +1283,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1340
1283
  throw new Error("Trace record missing required fields");
1341
1284
  }
1342
1285
  break;
1343
- case storage.TABLE_EVALS:
1344
- if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
1345
- throw new Error("Eval record missing required fields");
1346
- }
1347
- break;
1348
1286
  case storage.TABLE_SCORERS:
1349
1287
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1350
1288
  throw new Error("Score record missing required fields");
@@ -1362,12 +1300,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1362
1300
  async insert({ tableName, record }) {
1363
1301
  try {
1364
1302
  const key = this.getKey(tableName, record);
1365
- const processedRecord = {
1366
- ...record,
1367
- createdAt: record.createdAt ? storage.serializeDate(record.createdAt) : void 0,
1368
- updatedAt: record.updatedAt ? storage.serializeDate(record.updatedAt) : void 0,
1369
- metadata: record.metadata ? JSON.stringify(record.metadata) : ""
1370
- };
1303
+ const processedRecord = { ...record };
1371
1304
  await this.validateRecord(processedRecord, tableName);
1372
1305
  await this.putKV({ tableName, key, value: processedRecord });
1373
1306
  } catch (error$1) {
@@ -1384,22 +1317,12 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1384
1317
  );
1385
1318
  }
1386
1319
  }
1387
- ensureMetadata(metadata) {
1388
- if (!metadata) return {};
1389
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1390
- }
1391
1320
  async load({ tableName, keys }) {
1392
1321
  try {
1393
1322
  const key = this.getKey(tableName, keys);
1394
1323
  const data = await this.getKV(tableName, key);
1395
1324
  if (!data) return null;
1396
- const processed = {
1397
- ...data,
1398
- createdAt: storage.ensureDate(data.createdAt),
1399
- updatedAt: storage.ensureDate(data.updatedAt),
1400
- metadata: this.ensureMetadata(data.metadata)
1401
- };
1402
- return processed;
1325
+ return data;
1403
1326
  } catch (error$1) {
1404
1327
  const mastraError = new error.MastraError(
1405
1328
  {
@@ -1423,13 +1346,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1423
1346
  await Promise.all(
1424
1347
  input.records.map(async (record) => {
1425
1348
  const key = this.getKey(input.tableName, record);
1426
- const processedRecord = {
1427
- ...record,
1428
- createdAt: record.createdAt ? storage.serializeDate(record.createdAt) : void 0,
1429
- updatedAt: record.updatedAt ? storage.serializeDate(record.updatedAt) : void 0,
1430
- metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
1431
- };
1432
- await this.putKV({ tableName: input.tableName, key, value: processedRecord });
1349
+ await this.putKV({ tableName: input.tableName, key, value: record });
1433
1350
  })
1434
1351
  );
1435
1352
  } catch (error$1) {
@@ -1587,7 +1504,7 @@ function transformScoreRow(row) {
1587
1504
  deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1588
1505
  deserialized.metadata = storage.safelyParseJSON(row.metadata);
1589
1506
  deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1590
- deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1507
+ deserialized.requestContext = storage.safelyParseJSON(row.requestContext);
1591
1508
  deserialized.entity = storage.safelyParseJSON(row.entity);
1592
1509
  return deserialized;
1593
1510
  }
@@ -1620,11 +1537,24 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1620
1537
  }
1621
1538
  }
1622
1539
  async saveScore(score) {
1540
+ let parsedScore;
1541
+ try {
1542
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1543
+ } catch (error$1) {
1544
+ throw new error.MastraError(
1545
+ {
1546
+ id: "CLOUDFLARE_STORAGE_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1547
+ domain: error.ErrorDomain.STORAGE,
1548
+ category: error.ErrorCategory.USER,
1549
+ details: { scoreId: score.id }
1550
+ },
1551
+ error$1
1552
+ );
1553
+ }
1623
1554
  try {
1624
1555
  const id = crypto.randomUUID();
1625
- const { input, ...rest } = score;
1626
1556
  const serializedRecord = {};
1627
- for (const [key, value] of Object.entries(rest)) {
1557
+ for (const [key, value] of Object.entries(parsedScore)) {
1628
1558
  if (value !== null && value !== void 0) {
1629
1559
  if (typeof value === "object") {
1630
1560
  serializedRecord[key] = JSON.stringify(value);
@@ -1660,7 +1590,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1660
1590
  throw mastraError;
1661
1591
  }
1662
1592
  }
1663
- async getScoresByScorerId({
1593
+ async listScoresByScorerId({
1664
1594
  scorerId,
1665
1595
  entityId,
1666
1596
  entityType,
@@ -1690,15 +1620,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1690
1620
  const dateB = new Date(b.createdAt || 0).getTime();
1691
1621
  return dateB - dateA;
1692
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);
1693
1626
  const total = scores.length;
1694
- const start = pagination.page * pagination.perPage;
1695
- const end = start + pagination.perPage;
1627
+ const end = perPageInput === false ? scores.length : start + perPage;
1696
1628
  const pagedScores = scores.slice(start, end);
1697
1629
  return {
1698
1630
  pagination: {
1699
1631
  total,
1700
- page: pagination.page,
1701
- perPage: pagination.perPage,
1632
+ page,
1633
+ perPage: perPageForResponse,
1702
1634
  hasMore: end < total
1703
1635
  },
1704
1636
  scores: pagedScores
@@ -1718,7 +1650,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1718
1650
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1719
1651
  }
1720
1652
  }
1721
- async getScoresByRunId({
1653
+ async listScoresByRunId({
1722
1654
  runId,
1723
1655
  pagination
1724
1656
  }) {
@@ -1736,15 +1668,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1736
1668
  const dateB = new Date(b.createdAt || 0).getTime();
1737
1669
  return dateB - dateA;
1738
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);
1739
1674
  const total = scores.length;
1740
- const start = pagination.page * pagination.perPage;
1741
- const end = start + pagination.perPage;
1675
+ const end = perPageInput === false ? scores.length : start + perPage;
1742
1676
  const pagedScores = scores.slice(start, end);
1743
1677
  return {
1744
1678
  pagination: {
1745
1679
  total,
1746
- page: pagination.page,
1747
- perPage: pagination.perPage,
1680
+ page,
1681
+ perPage: perPageForResponse,
1748
1682
  hasMore: end < total
1749
1683
  },
1750
1684
  scores: pagedScores
@@ -1764,7 +1698,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1764
1698
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1765
1699
  }
1766
1700
  }
1767
- async getScoresByEntityId({
1701
+ async listScoresByEntityId({
1768
1702
  entityId,
1769
1703
  entityType,
1770
1704
  pagination
@@ -1783,15 +1717,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1783
1717
  const dateB = new Date(b.createdAt || 0).getTime();
1784
1718
  return dateB - dateA;
1785
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);
1786
1723
  const total = scores.length;
1787
- const start = pagination.page * pagination.perPage;
1788
- const end = start + pagination.perPage;
1724
+ const end = perPageInput === false ? scores.length : start + perPage;
1789
1725
  const pagedScores = scores.slice(start, end);
1790
1726
  return {
1791
1727
  pagination: {
1792
1728
  total,
1793
- page: pagination.page,
1794
- perPage: pagination.perPage,
1729
+ page,
1730
+ perPage: perPageForResponse,
1795
1731
  hasMore: end < total
1796
1732
  },
1797
1733
  scores: pagedScores
@@ -1811,126 +1747,55 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1811
1747
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1812
1748
  }
1813
1749
  }
1814
- };
1815
- var TracesStorageCloudflare = class extends storage.TracesStorage {
1816
- operations;
1817
- constructor({ operations }) {
1818
- super();
1819
- this.operations = operations;
1820
- }
1821
- async getTraces(args) {
1822
- const paginatedArgs = {
1823
- name: args.name,
1824
- scope: args.scope,
1825
- page: args.page,
1826
- perPage: args.perPage,
1827
- attributes: args.attributes,
1828
- filters: args.filters,
1829
- dateRange: args.fromDate || args.toDate ? {
1830
- start: args.fromDate,
1831
- end: args.toDate
1832
- } : void 0
1833
- };
1834
- try {
1835
- const result = await this.getTracesPaginated(paginatedArgs);
1836
- return result.traces;
1837
- } catch (error$1) {
1838
- throw new error.MastraError(
1839
- {
1840
- id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
1841
- domain: error.ErrorDomain.STORAGE,
1842
- category: error.ErrorCategory.THIRD_PARTY,
1843
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1844
- details: {
1845
- name: args.name ?? "",
1846
- scope: args.scope ?? ""
1847
- }
1848
- },
1849
- error$1
1850
- );
1851
- }
1852
- }
1853
- async getTracesPaginated(args) {
1750
+ async listScoresBySpan({
1751
+ traceId,
1752
+ spanId,
1753
+ pagination
1754
+ }) {
1854
1755
  try {
1855
- const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
1856
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
1857
- const keyObjs = await this.operations.listKV(storage.TABLE_TRACES, { prefix: `${prefix}${storage.TABLE_TRACES}` });
1858
- const traces = [];
1859
- for (const { name: key } of keyObjs) {
1860
- try {
1861
- const data = await this.operations.getKV(storage.TABLE_TRACES, key);
1862
- if (!data) continue;
1863
- if (name && data.name !== name) continue;
1864
- if (scope && data.scope !== scope) continue;
1865
- if (attributes) {
1866
- const dataAttributes = data.attributes || {};
1867
- let shouldSkip = false;
1868
- for (const [key2, value] of Object.entries(attributes)) {
1869
- if (dataAttributes[key2] !== value) {
1870
- shouldSkip = true;
1871
- break;
1872
- }
1873
- }
1874
- if (shouldSkip) continue;
1875
- }
1876
- if (dateRange?.start || dateRange?.end) {
1877
- const traceDate = new Date(data.createdAt || 0);
1878
- if (dateRange.start && traceDate < dateRange.start) continue;
1879
- if (dateRange.end && traceDate > dateRange.end) continue;
1880
- }
1881
- if (filters) {
1882
- let shouldSkip = false;
1883
- for (const [key2, value] of Object.entries(filters)) {
1884
- if (data[key2] !== value) {
1885
- shouldSkip = true;
1886
- break;
1887
- }
1888
- }
1889
- if (shouldSkip) continue;
1890
- }
1891
- traces.push(data);
1892
- } catch (err) {
1893
- this.logger.error("Failed to parse trace:", { key, error: err });
1756
+ const keys = await this.operations.listKV(storage.TABLE_SCORERS);
1757
+ const scores = [];
1758
+ for (const { name: key } of keys) {
1759
+ const score = await this.operations.getKV(storage.TABLE_SCORERS, key);
1760
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1761
+ scores.push(transformScoreRow(score));
1894
1762
  }
1895
1763
  }
1896
- traces.sort((a, b) => {
1897
- const aTime = new Date(a.createdAt || 0).getTime();
1898
- const bTime = new Date(b.createdAt || 0).getTime();
1899
- return bTime - aTime;
1764
+ scores.sort((a, b) => {
1765
+ const dateA = new Date(a.createdAt || 0).getTime();
1766
+ const dateB = new Date(b.createdAt || 0).getTime();
1767
+ return dateB - dateA;
1900
1768
  });
1901
- const total = traces.length;
1902
- const start = page * perPage;
1903
- const end = start + perPage;
1904
- const pagedTraces = traces.slice(start, end);
1769
+ const { page, perPage: perPageInput } = pagination;
1770
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1771
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1772
+ const total = scores.length;
1773
+ const end = perPageInput === false ? scores.length : start + perPage;
1774
+ const pagedScores = scores.slice(start, end);
1905
1775
  return {
1906
- traces: pagedTraces,
1907
- total,
1908
- page,
1909
- perPage,
1910
- hasMore: end < total
1776
+ pagination: {
1777
+ total,
1778
+ page,
1779
+ perPage: perPageForResponse,
1780
+ hasMore: end < total
1781
+ },
1782
+ scores: pagedScores
1911
1783
  };
1912
1784
  } catch (error$1) {
1913
1785
  const mastraError = new error.MastraError(
1914
1786
  {
1915
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1787
+ id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1916
1788
  domain: error.ErrorDomain.STORAGE,
1917
1789
  category: error.ErrorCategory.THIRD_PARTY,
1918
- text: "Error getting traces with pagination"
1790
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1919
1791
  },
1920
1792
  error$1
1921
1793
  );
1922
- this.logger.trackException?.(mastraError);
1923
- this.logger.error(mastraError.toString());
1924
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1794
+ this.logger?.trackException(mastraError);
1795
+ this.logger?.error(mastraError.toString());
1796
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1925
1797
  }
1926
1798
  }
1927
- async batchTraceInsert({ records }) {
1928
- this.logger.debug("Batch inserting traces", { count: records.length });
1929
- await this.operations.batchInsert({
1930
- tableName: storage.TABLE_TRACES,
1931
- records
1932
- });
1933
- }
1934
1799
  };
1935
1800
  var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1936
1801
  operations;
@@ -1949,7 +1814,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1949
1814
  // runId,
1950
1815
  // stepId,
1951
1816
  // result,
1952
- // runtimeContext,
1817
+ // requestContext,
1953
1818
  }) {
1954
1819
  throw new Error("Method not implemented.");
1955
1820
  }
@@ -1970,7 +1835,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1970
1835
  workflow_name: workflowName,
1971
1836
  run_id: runId,
1972
1837
  resourceId,
1973
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1838
+ snapshot: JSON.stringify(snapshot),
1974
1839
  createdAt: /* @__PURE__ */ new Date(),
1975
1840
  updatedAt: /* @__PURE__ */ new Date()
1976
1841
  }
@@ -2049,15 +1914,29 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2049
1914
  if (resourceId) key += `:${resourceId}`;
2050
1915
  return key;
2051
1916
  }
2052
- async getWorkflowRuns({
1917
+ async listWorkflowRuns({
2053
1918
  workflowName,
2054
- limit = 20,
2055
- offset = 0,
1919
+ page = 0,
1920
+ perPage = 20,
2056
1921
  resourceId,
2057
1922
  fromDate,
2058
- toDate
1923
+ toDate,
1924
+ status
2059
1925
  } = {}) {
2060
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;
2061
1940
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2062
1941
  const keyObjs = await this.operations.listKV(storage.TABLE_WORKFLOW_SNAPSHOT, { prefix });
2063
1942
  const runs = [];
@@ -2073,10 +1952,11 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2073
1952
  if (!data) continue;
2074
1953
  try {
2075
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;
2076
1957
  const createdAt = storage.ensureDate(data.createdAt);
2077
1958
  if (fromDate && createdAt && createdAt < fromDate) continue;
2078
1959
  if (toDate && createdAt && createdAt > toDate) continue;
2079
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2080
1960
  const resourceIdToUse = keyResourceId || data.resourceId;
2081
1961
  const run = this.parseWorkflowRun({
2082
1962
  ...data,
@@ -2094,7 +1974,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2094
1974
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2095
1975
  return bDate - aDate;
2096
1976
  });
2097
- const pagedRuns = runs.slice(offset, offset + limit);
1977
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2098
1978
  return {
2099
1979
  runs: pagedRuns,
2100
1980
  total: runs.length
@@ -2102,7 +1982,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2102
1982
  } catch (error$1) {
2103
1983
  const mastraError = new error.MastraError(
2104
1984
  {
2105
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
1985
+ id: "CLOUDFLARE_STORAGE_LIST_WORKFLOW_RUNS_FAILED",
2106
1986
  domain: error.ErrorDomain.STORAGE,
2107
1987
  category: error.ErrorCategory.THIRD_PARTY
2108
1988
  },
@@ -2176,14 +2056,7 @@ var CloudflareStore = class extends storage.MastraStorage {
2176
2056
  if (!config.bindings) {
2177
2057
  throw new Error("KV bindings are required when using Workers Binding API");
2178
2058
  }
2179
- const requiredTables = [
2180
- storage.TABLE_THREADS,
2181
- storage.TABLE_MESSAGES,
2182
- storage.TABLE_WORKFLOW_SNAPSHOT,
2183
- storage.TABLE_EVALS,
2184
- storage.TABLE_SCORERS,
2185
- storage.TABLE_TRACES
2186
- ];
2059
+ const requiredTables = [storage.TABLE_THREADS, storage.TABLE_MESSAGES, storage.TABLE_WORKFLOW_SNAPSHOT, storage.TABLE_SCORERS];
2187
2060
  for (const table of requiredTables) {
2188
2061
  if (!(table in config.bindings)) {
2189
2062
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2201,8 +2074,15 @@ var CloudflareStore = class extends storage.MastraStorage {
2201
2074
  throw new Error("apiToken is required for REST API");
2202
2075
  }
2203
2076
  }
2077
+ get supports() {
2078
+ const supports = super.supports;
2079
+ supports.listScoresBySpan = true;
2080
+ supports.resourceWorkingMemory = true;
2081
+ supports.selectByIncludeResourceScope = true;
2082
+ return supports;
2083
+ }
2204
2084
  constructor(config) {
2205
- super({ name: "Cloudflare" });
2085
+ super({ id: config.id, name: "Cloudflare" });
2206
2086
  try {
2207
2087
  if (isWorkersConfig(config)) {
2208
2088
  this.validateWorkersConfig(config);
@@ -2224,15 +2104,9 @@ var CloudflareStore = class extends storage.MastraStorage {
2224
2104
  namespacePrefix: this.namespacePrefix,
2225
2105
  bindings: this.bindings
2226
2106
  });
2227
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2228
- operations
2229
- });
2230
2107
  const workflows = new WorkflowsStorageCloudflare({
2231
2108
  operations
2232
2109
  });
2233
- const traces = new TracesStorageCloudflare({
2234
- operations
2235
- });
2236
2110
  const memory = new MemoryStorageCloudflare({
2237
2111
  operations
2238
2112
  });
@@ -2241,9 +2115,7 @@ var CloudflareStore = class extends storage.MastraStorage {
2241
2115
  });
2242
2116
  this.stores = {
2243
2117
  operations,
2244
- legacyEvals,
2245
2118
  workflows,
2246
- traces,
2247
2119
  memory,
2248
2120
  scores
2249
2121
  };
@@ -2285,9 +2157,6 @@ var CloudflareStore = class extends storage.MastraStorage {
2285
2157
  async getThreadById({ threadId }) {
2286
2158
  return this.stores.memory.getThreadById({ threadId });
2287
2159
  }
2288
- async getThreadsByResourceId({ resourceId }) {
2289
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2290
- }
2291
2160
  async saveThread({ thread }) {
2292
2161
  return this.stores.memory.saveThread({ thread });
2293
2162
  }
@@ -2304,22 +2173,14 @@ var CloudflareStore = class extends storage.MastraStorage {
2304
2173
  async saveMessages(args) {
2305
2174
  return this.stores.memory.saveMessages(args);
2306
2175
  }
2307
- async getMessages({
2308
- threadId,
2309
- resourceId,
2310
- selectBy,
2311
- format
2312
- }) {
2313
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2314
- }
2315
2176
  async updateWorkflowResults({
2316
2177
  workflowName,
2317
2178
  runId,
2318
2179
  stepId,
2319
2180
  result,
2320
- runtimeContext
2181
+ requestContext
2321
2182
  }) {
2322
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2183
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2323
2184
  }
2324
2185
  async updateWorkflowState({
2325
2186
  workflowName,
@@ -2328,11 +2189,8 @@ var CloudflareStore = class extends storage.MastraStorage {
2328
2189
  }) {
2329
2190
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2330
2191
  }
2331
- async getMessagesById({
2332
- messageIds,
2333
- format
2334
- }) {
2335
- return this.stores.memory.getMessagesById({ messageIds, format });
2192
+ async listMessagesById({ messageIds }) {
2193
+ return this.stores.memory.listMessagesById({ messageIds });
2336
2194
  }
2337
2195
  async persistWorkflowSnapshot(params) {
2338
2196
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2343,46 +2201,23 @@ var CloudflareStore = class extends storage.MastraStorage {
2343
2201
  async batchInsert(input) {
2344
2202
  return this.stores.operations.batchInsert(input);
2345
2203
  }
2346
- async getTraces({
2347
- name,
2348
- scope,
2349
- page = 0,
2350
- perPage = 100,
2351
- attributes,
2352
- fromDate,
2353
- toDate
2354
- }) {
2355
- return this.stores.traces.getTraces({
2356
- name,
2357
- scope,
2358
- page,
2359
- perPage,
2360
- attributes,
2361
- fromDate,
2362
- toDate
2363
- });
2364
- }
2365
- async getEvalsByAgentName(agentName, type) {
2366
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2367
- }
2368
- async getEvals(options) {
2369
- return this.stores.legacyEvals.getEvals(options);
2370
- }
2371
- async getWorkflowRuns({
2204
+ async listWorkflowRuns({
2372
2205
  workflowName,
2373
- limit = 20,
2374
- offset = 0,
2206
+ perPage = 20,
2207
+ page = 0,
2375
2208
  resourceId,
2376
2209
  fromDate,
2377
- toDate
2210
+ toDate,
2211
+ status
2378
2212
  } = {}) {
2379
- return this.stores.workflows.getWorkflowRuns({
2213
+ return this.stores.workflows.listWorkflowRuns({
2380
2214
  workflowName,
2381
- limit,
2382
- offset,
2215
+ perPage,
2216
+ page,
2383
2217
  resourceId,
2384
2218
  fromDate,
2385
- toDate
2219
+ toDate,
2220
+ status
2386
2221
  });
2387
2222
  }
2388
2223
  async getWorkflowRunById({
@@ -2391,15 +2226,6 @@ var CloudflareStore = class extends storage.MastraStorage {
2391
2226
  }) {
2392
2227
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2393
2228
  }
2394
- async getTracesPaginated(args) {
2395
- return this.stores.traces.getTracesPaginated(args);
2396
- }
2397
- async getThreadsByResourceIdPaginated(args) {
2398
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2399
- }
2400
- async getMessagesPaginated(args) {
2401
- return this.stores.memory.getMessagesPaginated(args);
2402
- }
2403
2229
  async updateMessages(args) {
2404
2230
  return this.stores.memory.updateMessages(args);
2405
2231
  }
@@ -2409,27 +2235,34 @@ var CloudflareStore = class extends storage.MastraStorage {
2409
2235
  async saveScore(score) {
2410
2236
  return this.stores.scores.saveScore(score);
2411
2237
  }
2412
- async getScoresByRunId({
2238
+ async listScoresByRunId({
2413
2239
  runId,
2414
2240
  pagination
2415
2241
  }) {
2416
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2242
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2417
2243
  }
2418
- async getScoresByEntityId({
2244
+ async listScoresByEntityId({
2419
2245
  entityId,
2420
2246
  entityType,
2421
2247
  pagination
2422
2248
  }) {
2423
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2249
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2424
2250
  }
2425
- async getScoresByScorerId({
2251
+ async listScoresByScorerId({
2426
2252
  scorerId,
2427
2253
  entityId,
2428
2254
  entityType,
2429
2255
  source,
2430
2256
  pagination
2431
2257
  }) {
2432
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2258
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2259
+ }
2260
+ async listScoresBySpan({
2261
+ traceId,
2262
+ spanId,
2263
+ pagination
2264
+ }) {
2265
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2433
2266
  }
2434
2267
  async getResourceById({ resourceId }) {
2435
2268
  return this.stores.memory.getResourceById({ resourceId });