@mastra/cloudflare 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-top-level-fix-20251211103030

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;
@@ -133,7 +45,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
133
45
  } catch (error$1) {
134
46
  const mastraError = new error.MastraError(
135
47
  {
136
- id: "CLOUDFLARE_STORAGE_GET_THREAD_BY_ID_FAILED",
48
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_THREAD_BY_ID", "FAILED"),
137
49
  domain: error.ErrorDomain.STORAGE,
138
50
  category: error.ErrorCategory.THIRD_PARTY,
139
51
  details: {
@@ -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.createStorageErrorId("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: storage.createStorageErrorId("CLOUDFLARE", "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"
@@ -245,7 +118,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
245
118
  } catch (error$1) {
246
119
  throw new error.MastraError(
247
120
  {
248
- id: "CLOUDFLARE_STORAGE_SAVE_THREAD_FAILED",
121
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_THREAD", "FAILED"),
249
122
  domain: error.ErrorDomain.STORAGE,
250
123
  category: error.ErrorCategory.THIRD_PARTY,
251
124
  details: {
@@ -280,7 +153,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
280
153
  } catch (error$1) {
281
154
  throw new error.MastraError(
282
155
  {
283
- id: "CLOUDFLARE_STORAGE_UPDATE_THREAD_FAILED",
156
+ id: storage.createStorageErrorId("CLOUDFLARE", "UPDATE_THREAD", "FAILED"),
284
157
  domain: error.ErrorDomain.STORAGE,
285
158
  category: error.ErrorCategory.THIRD_PARTY,
286
159
  details: {
@@ -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
  }
@@ -329,7 +202,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
329
202
  } catch (error$1) {
330
203
  throw new error.MastraError(
331
204
  {
332
- id: "CLOUDFLARE_STORAGE_DELETE_THREAD_FAILED",
205
+ id: storage.createStorageErrorId("CLOUDFLARE", "DELETE_THREAD", "FAILED"),
333
206
  domain: error.ErrorDomain.STORAGE,
334
207
  category: error.ErrorCategory.THIRD_PARTY,
335
208
  details: {
@@ -340,6 +213,17 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
340
213
  );
341
214
  }
342
215
  }
216
+ /**
217
+ * Searches all threads in the KV store to find a message by its ID.
218
+ *
219
+ * **Performance Warning**: This method sequentially scans all threads to locate
220
+ * the message. For stores with many threads, this can result in significant
221
+ * latency and API calls. When possible, callers should provide the `threadId`
222
+ * directly to avoid this full scan.
223
+ *
224
+ * @param messageId - The globally unique message ID to search for
225
+ * @returns The message with its threadId if found, null otherwise
226
+ */
343
227
  async findMessageInAnyThread(messageId) {
344
228
  try {
345
229
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
@@ -396,7 +280,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
396
280
  });
397
281
  } catch (error) {
398
282
  const message = error instanceof Error ? error.message : String(error);
399
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
283
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
400
284
  throw error;
401
285
  } finally {
402
286
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -414,7 +298,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
414
298
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
415
299
  return Array.isArray(arr) ? arr : [];
416
300
  } catch (e) {
417
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
301
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
418
302
  return [];
419
303
  }
420
304
  }
@@ -445,8 +329,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
445
329
  }
446
330
  }
447
331
  async saveMessages(args) {
448
- const { messages, format = "v1" } = args;
449
- if (!Array.isArray(messages) || messages.length === 0) return [];
332
+ const { messages } = args;
333
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
450
334
  try {
451
335
  const validatedMessages = messages.map((message, index) => {
452
336
  const errors = [];
@@ -469,9 +353,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
469
353
  const messageMigrationTasks = [];
470
354
  for (const message of validatedMessages) {
471
355
  const existingMessage = await this.findMessageInAnyThread(message.id);
472
- console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
356
+ this.logger?.debug(
357
+ `Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`
358
+ );
473
359
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
474
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
360
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
475
361
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
476
362
  }
477
363
  }
@@ -500,10 +386,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
500
386
  ...cleanMessage,
501
387
  createdAt: storage.serializeDate(cleanMessage.createdAt)
502
388
  };
503
- console.log(`Saving message ${message.id} with content:`, {
504
- content: serializedMessage.content,
505
- contentType: typeof serializedMessage.content,
506
- isArray: Array.isArray(serializedMessage.content)
389
+ this.logger?.debug(`Saving message ${message.id}`, {
390
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
507
391
  });
508
392
  await this.operations.putKV({ tableName: storage.TABLE_MESSAGES, key, value: serializedMessage });
509
393
  })
@@ -523,7 +407,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
523
407
  } catch (error$1) {
524
408
  throw new error.MastraError(
525
409
  {
526
- id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
410
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
527
411
  domain: error.ErrorDomain.STORAGE,
528
412
  category: error.ErrorCategory.THIRD_PARTY,
529
413
  details: {
@@ -539,12 +423,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
539
423
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
540
424
  );
541
425
  const list = new agent.MessageList().add(prepared, "memory");
542
- if (format === `v2`) return list.get.all.v2();
543
- return list.get.all.v1();
426
+ return { messages: list.get.all.db() };
544
427
  } catch (error$1) {
545
428
  throw new error.MastraError(
546
429
  {
547
- id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
430
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
548
431
  domain: error.ErrorDomain.STORAGE,
549
432
  category: error.ErrorCategory.THIRD_PARTY
550
433
  },
@@ -570,10 +453,25 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
570
453
  async getFullOrder(orderKey) {
571
454
  return this.getRange(orderKey, 0, -1);
572
455
  }
573
- async getIncludedMessagesWithContext(threadId, include, messageIds) {
456
+ /**
457
+ * Retrieves messages specified in the include array along with their surrounding context.
458
+ *
459
+ * **Performance Note**: When `threadId` is not provided in an include entry, this method
460
+ * must call `findMessageInAnyThread` which sequentially scans all threads in the KV store.
461
+ * For optimal performance, callers should provide `threadId` in include entries when known.
462
+ *
463
+ * @param include - Array of message IDs to include, optionally with context windows
464
+ * @param messageIds - Set to accumulate the message IDs that should be fetched
465
+ */
466
+ async getIncludedMessagesWithContext(include, messageIds) {
574
467
  await Promise.all(
575
468
  include.map(async (item) => {
576
- const targetThreadId = item.threadId || threadId;
469
+ let targetThreadId = item.threadId;
470
+ if (!targetThreadId) {
471
+ const foundMessage = await this.findMessageInAnyThread(item.id);
472
+ if (!foundMessage) return;
473
+ targetThreadId = foundMessage.threadId;
474
+ }
577
475
  if (!targetThreadId) return;
578
476
  const threadMessagesKey = this.getThreadMessagesKey(targetThreadId);
579
477
  messageIds.add(item.id);
@@ -603,9 +501,16 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
603
501
  const latestIds = await this.getLastN(threadMessagesKey, limit);
604
502
  latestIds.forEach((id) => messageIds.add(id));
605
503
  } catch {
606
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
504
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
607
505
  }
608
506
  }
507
+ /**
508
+ * Fetches and parses messages from one or more threads.
509
+ *
510
+ * **Performance Note**: When neither `include` entries with `threadId` nor `targetThreadId`
511
+ * are provided, this method falls back to `findMessageInAnyThread` which scans all threads.
512
+ * For optimal performance, provide `threadId` in include entries or specify `targetThreadId`.
513
+ */
609
514
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
610
515
  const messageIdToThreadId = /* @__PURE__ */ new Map();
611
516
  if (include) {
@@ -634,111 +539,29 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
634
539
  const data = await this.operations.getKV(storage.TABLE_MESSAGES, key);
635
540
  if (!data) return null;
636
541
  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)
542
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
543
+ contentSummary: this.summarizeMessageContent(parsed.content)
641
544
  });
642
545
  return parsed;
643
546
  } catch (error) {
644
547
  const message = error instanceof Error ? error.message : String(error);
645
- this.logger.error(`Error retrieving message ${id}:`, { message });
548
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
646
549
  return null;
647
550
  }
648
551
  })
649
552
  );
650
553
  return messages.filter((msg) => msg !== null);
651
554
  }
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 [];
555
+ /**
556
+ * Retrieves messages by their IDs.
557
+ *
558
+ * **Performance Warning**: This method calls `findMessageInAnyThread` for each message ID,
559
+ * which scans all threads in the KV store. For large numbers of messages or threads,
560
+ * this can result in significant latency. Consider using `listMessages` with specific
561
+ * thread IDs when the thread context is known.
562
+ */
563
+ async listMessagesById({ messageIds }) {
564
+ if (messageIds.length === 0) return { messages: [] };
742
565
  try {
743
566
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
744
567
  (result) => !!result
@@ -749,12 +572,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
749
572
  createdAt: storage.ensureDate(message.createdAt)
750
573
  }));
751
574
  const list = new agent.MessageList().add(prepared, "memory");
752
- if (format === `v1`) return list.get.all.v1();
753
- return list.get.all.v2();
575
+ return { messages: list.get.all.db() };
754
576
  } catch (error$1) {
755
577
  const mastraError = new error.MastraError(
756
578
  {
757
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
579
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES_BY_ID", "FAILED"),
758
580
  domain: error.ErrorDomain.STORAGE,
759
581
  category: error.ErrorCategory.THIRD_PARTY,
760
582
  text: `Error retrieving messages by ID`,
@@ -766,52 +588,198 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
766
588
  );
767
589
  this.logger?.trackException(mastraError);
768
590
  this.logger?.error(mastraError.toString());
769
- return [];
591
+ return { messages: [] };
770
592
  }
771
593
  }
772
- async getMessagesPaginated(args) {
773
- const { threadId, resourceId, selectBy, format = "v1" } = args;
774
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
594
+ async listMessages(args) {
595
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
596
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
597
+ const isValidThreadId = (id) => typeof id === "string" && id.trim().length > 0;
598
+ if (threadIds.length === 0 || threadIds.some((id) => !isValidThreadId(id))) {
599
+ throw new error.MastraError(
600
+ {
601
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_THREAD_ID"),
602
+ domain: error.ErrorDomain.STORAGE,
603
+ category: error.ErrorCategory.THIRD_PARTY,
604
+ details: { threadId: Array.isArray(threadId) ? JSON.stringify(threadId) : String(threadId) }
605
+ },
606
+ new Error("threadId must be a non-empty string or array of non-empty strings")
607
+ );
608
+ }
609
+ const perPage = storage.normalizePerPage(perPageInput, 40);
610
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
775
611
  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" });
778
- 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;
612
+ if (page < 0) {
613
+ throw new error.MastraError(
614
+ {
615
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_PAGE"),
616
+ domain: error.ErrorDomain.STORAGE,
617
+ category: error.ErrorCategory.USER,
618
+ details: { page }
619
+ },
620
+ new Error("page must be >= 0")
621
+ );
622
+ }
623
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
624
+ const threadMessageIds = /* @__PURE__ */ new Set();
625
+ for (const tid of threadIds) {
626
+ try {
627
+ const threadMessagesKey = this.getThreadMessagesKey(tid);
628
+ const allIds = await this.getFullOrder(threadMessagesKey);
629
+ allIds.forEach((id) => threadMessageIds.add(id));
630
+ } catch {
631
+ }
632
+ }
633
+ const threadMessages = await this.fetchAndParseMessagesFromMultipleThreads(
634
+ Array.from(threadMessageIds),
635
+ void 0,
636
+ threadIds.length === 1 ? threadIds[0] : void 0
637
+ );
638
+ let filteredThreadMessages = threadMessages;
639
+ if (resourceId) {
640
+ filteredThreadMessages = filteredThreadMessages.filter((msg) => msg.resourceId === resourceId);
641
+ }
642
+ const dateRange = filter?.dateRange;
643
+ if (dateRange) {
644
+ filteredThreadMessages = filteredThreadMessages.filter((msg) => {
645
+ const messageDate = new Date(msg.createdAt);
646
+ if (dateRange.start && messageDate < new Date(dateRange.start)) return false;
647
+ if (dateRange.end && messageDate > new Date(dateRange.end)) return false;
785
648
  return true;
786
649
  });
787
650
  }
788
- const start = page * perPage;
789
- const end = start + perPage;
790
- const paginatedMessages = filteredMessages.slice(start, end);
651
+ const total = filteredThreadMessages.length;
652
+ if (perPage === 0 && (!include || include.length === 0)) {
653
+ return {
654
+ messages: [],
655
+ total,
656
+ page,
657
+ perPage: perPageForResponse,
658
+ hasMore: offset < total
659
+ };
660
+ }
661
+ filteredThreadMessages.sort((a, b) => {
662
+ const timeA = new Date(a.createdAt).getTime();
663
+ const timeB = new Date(b.createdAt).getTime();
664
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
665
+ if (timeDiff === 0) {
666
+ return a.id.localeCompare(b.id);
667
+ }
668
+ return timeDiff;
669
+ });
670
+ let paginatedMessages;
671
+ if (perPage === 0) {
672
+ paginatedMessages = [];
673
+ } else if (perPage === Number.MAX_SAFE_INTEGER) {
674
+ paginatedMessages = filteredThreadMessages;
675
+ } else {
676
+ paginatedMessages = filteredThreadMessages.slice(offset, offset + perPage);
677
+ }
678
+ let includedMessages = [];
679
+ if (include && include.length > 0) {
680
+ const includedMessageIds = /* @__PURE__ */ new Set();
681
+ await this.getIncludedMessagesWithContext(include, includedMessageIds);
682
+ const paginatedIds = new Set(paginatedMessages.map((m) => m.id));
683
+ const idsToFetch = Array.from(includedMessageIds).filter((id) => !paginatedIds.has(id));
684
+ if (idsToFetch.length > 0) {
685
+ includedMessages = await this.fetchAndParseMessagesFromMultipleThreads(idsToFetch, include, void 0);
686
+ }
687
+ }
688
+ const seenIds = /* @__PURE__ */ new Set();
689
+ const allMessages = [];
690
+ for (const msg of paginatedMessages) {
691
+ if (!seenIds.has(msg.id)) {
692
+ allMessages.push(msg);
693
+ seenIds.add(msg.id);
694
+ }
695
+ }
696
+ for (const msg of includedMessages) {
697
+ if (!seenIds.has(msg.id)) {
698
+ allMessages.push(msg);
699
+ seenIds.add(msg.id);
700
+ }
701
+ }
702
+ allMessages.sort((a, b) => {
703
+ const timeA = new Date(a.createdAt).getTime();
704
+ const timeB = new Date(b.createdAt).getTime();
705
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
706
+ if (timeDiff === 0) {
707
+ return a.id.localeCompare(b.id);
708
+ }
709
+ return timeDiff;
710
+ });
711
+ let filteredMessages = allMessages;
712
+ const paginatedCount = paginatedMessages.length;
713
+ if (total === 0 && filteredMessages.length === 0 && (!include || include.length === 0)) {
714
+ return {
715
+ messages: [],
716
+ total: 0,
717
+ page,
718
+ perPage: perPageForResponse,
719
+ hasMore: false
720
+ };
721
+ }
722
+ const prepared = filteredMessages.map(({ _index, ...message }) => ({
723
+ ...message,
724
+ type: message.type !== "v2" ? message.type : void 0,
725
+ createdAt: storage.ensureDate(message.createdAt)
726
+ }));
727
+ const primaryThreadId = Array.isArray(threadId) ? threadId[0] : threadId;
728
+ const list = new agent.MessageList({ threadId: primaryThreadId, resourceId }).add(
729
+ prepared,
730
+ "memory"
731
+ );
732
+ let finalMessages = list.get.all.db();
733
+ finalMessages = finalMessages.sort((a, b) => {
734
+ const isDateField = field === "createdAt" || field === "updatedAt";
735
+ const aVal = isDateField ? new Date(a[field]).getTime() : a[field];
736
+ const bVal = isDateField ? new Date(b[field]).getTime() : b[field];
737
+ if (aVal == null && bVal == null) return a.id.localeCompare(b.id);
738
+ if (aVal == null) return 1;
739
+ if (bVal == null) return -1;
740
+ if (typeof aVal === "number" && typeof bVal === "number") {
741
+ const cmp2 = direction === "ASC" ? aVal - bVal : bVal - aVal;
742
+ return cmp2 !== 0 ? cmp2 : a.id.localeCompare(b.id);
743
+ }
744
+ const cmp = direction === "ASC" ? String(aVal).localeCompare(String(bVal)) : String(bVal).localeCompare(String(aVal));
745
+ return cmp !== 0 ? cmp : a.id.localeCompare(b.id);
746
+ });
747
+ const threadIdSet = new Set(threadIds);
748
+ const returnedThreadMessageIds = new Set(
749
+ finalMessages.filter((m) => m.threadId && threadIdSet.has(m.threadId)).map((m) => m.id)
750
+ );
751
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
752
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + paginatedCount < total;
791
753
  return {
754
+ messages: finalMessages,
755
+ total,
792
756
  page,
793
- perPage,
794
- total: filteredMessages.length,
795
- hasMore: start + perPage < filteredMessages.length,
796
- messages: paginatedMessages
757
+ perPage: perPageForResponse,
758
+ hasMore
797
759
  };
798
760
  } catch (error$1) {
799
761
  const mastraError = new error.MastraError(
800
762
  {
801
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
763
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "FAILED"),
802
764
  domain: error.ErrorDomain.STORAGE,
803
765
  category: error.ErrorCategory.THIRD_PARTY,
804
- text: "Failed to get messages with pagination",
766
+ text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
805
767
  details: {
806
- threadId,
768
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
807
769
  resourceId: resourceId ?? ""
808
770
  }
809
771
  },
810
772
  error$1
811
773
  );
812
- this.logger?.trackException?.(mastraError);
813
774
  this.logger?.error?.(mastraError.toString());
814
- return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
775
+ this.logger?.trackException?.(mastraError);
776
+ return {
777
+ messages: [],
778
+ total: 0,
779
+ page,
780
+ perPage: perPageForResponse,
781
+ hasMore: false
782
+ };
815
783
  }
816
784
  }
817
785
  async updateMessages(args) {
@@ -914,7 +882,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
914
882
  } catch (error$1) {
915
883
  throw new error.MastraError(
916
884
  {
917
- id: "CLOUDFLARE_STORAGE_UPDATE_MESSAGES_FAILED",
885
+ id: storage.createStorageErrorId("CLOUDFLARE", "UPDATE_MESSAGES", "FAILED"),
918
886
  domain: error.ErrorDomain.STORAGE,
919
887
  category: error.ErrorCategory.THIRD_PARTY,
920
888
  text: "Failed to update messages"
@@ -937,7 +905,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
937
905
  } catch (error$1) {
938
906
  const mastraError = new error.MastraError(
939
907
  {
940
- id: "CLOUDFLARE_STORAGE_GET_RESOURCE_BY_ID_FAILED",
908
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_RESOURCE_BY_ID", "FAILED"),
941
909
  domain: error.ErrorDomain.STORAGE,
942
910
  category: error.ErrorCategory.THIRD_PARTY,
943
911
  details: {
@@ -966,7 +934,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
966
934
  } catch (error$1) {
967
935
  throw new error.MastraError(
968
936
  {
969
- id: "CLOUDFLARE_STORAGE_SAVE_RESOURCE_FAILED",
937
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_RESOURCE", "FAILED"),
970
938
  domain: error.ErrorDomain.STORAGE,
971
939
  category: error.ErrorCategory.THIRD_PARTY,
972
940
  details: {
@@ -1037,7 +1005,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1037
1005
  } catch (error$1) {
1038
1006
  throw new error.MastraError(
1039
1007
  {
1040
- id: "CLOUDFLARE_STORAGE_CLEAR_TABLE_FAILED",
1008
+ id: storage.createStorageErrorId("CLOUDFLARE", "CLEAR_TABLE", "FAILED"),
1041
1009
  domain: error.ErrorDomain.STORAGE,
1042
1010
  category: error.ErrorCategory.THIRD_PARTY,
1043
1011
  details: {
@@ -1057,7 +1025,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1057
1025
  } catch (error$1) {
1058
1026
  throw new error.MastraError(
1059
1027
  {
1060
- id: "CLOUDFLARE_STORAGE_DROP_TABLE_FAILED",
1028
+ id: storage.createStorageErrorId("CLOUDFLARE", "DROP_TABLE", "FAILED"),
1061
1029
  domain: error.ErrorDomain.STORAGE,
1062
1030
  category: error.ErrorCategory.THIRD_PARTY,
1063
1031
  details: {
@@ -1097,10 +1065,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1097
1065
  case storage.TABLE_TRACES:
1098
1066
  if (!record.id) throw new Error("Trace ID is required");
1099
1067
  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
1068
  case storage.TABLE_SCORERS:
1105
1069
  if (!record.id) throw new Error("Score ID is required");
1106
1070
  return `${prefix}${tableName}:${record.id}`;
@@ -1340,11 +1304,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1340
1304
  throw new Error("Trace record missing required fields");
1341
1305
  }
1342
1306
  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
1307
  case storage.TABLE_SCORERS:
1349
1308
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1350
1309
  throw new Error("Score record missing required fields");
@@ -1362,18 +1321,13 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1362
1321
  async insert({ tableName, record }) {
1363
1322
  try {
1364
1323
  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
- };
1324
+ const processedRecord = { ...record };
1371
1325
  await this.validateRecord(processedRecord, tableName);
1372
1326
  await this.putKV({ tableName, key, value: processedRecord });
1373
1327
  } catch (error$1) {
1374
1328
  throw new error.MastraError(
1375
1329
  {
1376
- id: "CLOUDFLARE_STORAGE_INSERT_FAILED",
1330
+ id: storage.createStorageErrorId("CLOUDFLARE", "INSERT", "FAILED"),
1377
1331
  domain: error.ErrorDomain.STORAGE,
1378
1332
  category: error.ErrorCategory.THIRD_PARTY,
1379
1333
  details: {
@@ -1384,26 +1338,16 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1384
1338
  );
1385
1339
  }
1386
1340
  }
1387
- ensureMetadata(metadata) {
1388
- if (!metadata) return {};
1389
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1390
- }
1391
1341
  async load({ tableName, keys }) {
1392
1342
  try {
1393
1343
  const key = this.getKey(tableName, keys);
1394
1344
  const data = await this.getKV(tableName, key);
1395
1345
  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;
1346
+ return data;
1403
1347
  } catch (error$1) {
1404
1348
  const mastraError = new error.MastraError(
1405
1349
  {
1406
- id: "CLOUDFLARE_STORAGE_LOAD_FAILED",
1350
+ id: storage.createStorageErrorId("CLOUDFLARE", "LOAD", "FAILED"),
1407
1351
  domain: error.ErrorDomain.STORAGE,
1408
1352
  category: error.ErrorCategory.THIRD_PARTY,
1409
1353
  details: {
@@ -1423,19 +1367,13 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1423
1367
  await Promise.all(
1424
1368
  input.records.map(async (record) => {
1425
1369
  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 });
1370
+ await this.putKV({ tableName: input.tableName, key, value: record });
1433
1371
  })
1434
1372
  );
1435
1373
  } catch (error$1) {
1436
1374
  throw new error.MastraError(
1437
1375
  {
1438
- id: "CLOUDFLARE_STORAGE_BATCH_INSERT_FAILED",
1376
+ id: storage.createStorageErrorId("CLOUDFLARE", "BATCH_INSERT", "FAILED"),
1439
1377
  domain: error.ErrorDomain.STORAGE,
1440
1378
  category: error.ErrorCategory.THIRD_PARTY,
1441
1379
  text: `Error in batch insert for table ${input.tableName}`,
@@ -1507,7 +1445,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1507
1445
  } catch (error$1) {
1508
1446
  throw new error.MastraError(
1509
1447
  {
1510
- id: "CLOUDFLARE_STORAGE_CREATE_TABLE_FAILED",
1448
+ id: storage.createStorageErrorId("CLOUDFLARE", "CREATE_TABLE", "FAILED"),
1511
1449
  domain: error.ErrorDomain.STORAGE,
1512
1450
  category: error.ErrorCategory.THIRD_PARTY,
1513
1451
  details: {
@@ -1539,7 +1477,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1539
1477
  } catch (error$1) {
1540
1478
  throw new error.MastraError(
1541
1479
  {
1542
- id: "CLOUDFLARE_STORAGE_LIST_NAMESPACE_KEYS_FAILED",
1480
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_NAMESPACE_KEYS", "FAILED"),
1543
1481
  domain: error.ErrorDomain.STORAGE,
1544
1482
  category: error.ErrorCategory.THIRD_PARTY,
1545
1483
  details: {
@@ -1579,17 +1517,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1579
1517
  }
1580
1518
  };
1581
1519
  function transformScoreRow(row) {
1582
- const deserialized = { ...row };
1583
- deserialized.input = storage.safelyParseJSON(row.input);
1584
- deserialized.output = storage.safelyParseJSON(row.output);
1585
- deserialized.scorer = storage.safelyParseJSON(row.scorer);
1586
- deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1587
- deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1588
- deserialized.metadata = storage.safelyParseJSON(row.metadata);
1589
- deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1590
- deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1591
- deserialized.entity = storage.safelyParseJSON(row.entity);
1592
- return deserialized;
1520
+ return storage.transformScoreRow(row);
1593
1521
  }
1594
1522
  var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1595
1523
  operations;
@@ -1607,7 +1535,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1607
1535
  } catch (error$1) {
1608
1536
  const mastraError = new error.MastraError(
1609
1537
  {
1610
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORE_BY_ID_FAILED",
1538
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORE_BY_ID", "FAILED"),
1611
1539
  domain: error.ErrorDomain.STORAGE,
1612
1540
  category: error.ErrorCategory.THIRD_PARTY,
1613
1541
  text: `Failed to get score by id: ${id}`
@@ -1620,11 +1548,30 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1620
1548
  }
1621
1549
  }
1622
1550
  async saveScore(score) {
1551
+ let parsedScore;
1552
+ try {
1553
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1554
+ } catch (error$1) {
1555
+ throw new error.MastraError(
1556
+ {
1557
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "VALIDATION_FAILED"),
1558
+ domain: error.ErrorDomain.STORAGE,
1559
+ category: error.ErrorCategory.USER,
1560
+ details: {
1561
+ scorer: score.scorer?.id ?? "unknown",
1562
+ entityId: score.entityId ?? "unknown",
1563
+ entityType: score.entityType ?? "unknown",
1564
+ traceId: score.traceId ?? "",
1565
+ spanId: score.spanId ?? ""
1566
+ }
1567
+ },
1568
+ error$1
1569
+ );
1570
+ }
1571
+ const id = crypto.randomUUID();
1623
1572
  try {
1624
- const id = crypto.randomUUID();
1625
- const { input, ...rest } = score;
1626
1573
  const serializedRecord = {};
1627
- for (const [key, value] of Object.entries(rest)) {
1574
+ for (const [key, value] of Object.entries(parsedScore)) {
1628
1575
  if (value !== null && value !== void 0) {
1629
1576
  if (typeof value === "object") {
1630
1577
  serializedRecord[key] = JSON.stringify(value);
@@ -1635,23 +1582,23 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1635
1582
  serializedRecord[key] = null;
1636
1583
  }
1637
1584
  }
1585
+ const now = /* @__PURE__ */ new Date();
1638
1586
  serializedRecord.id = id;
1639
- serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1640
- serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1587
+ serializedRecord.createdAt = now.toISOString();
1588
+ serializedRecord.updatedAt = now.toISOString();
1641
1589
  await this.operations.putKV({
1642
1590
  tableName: storage.TABLE_SCORERS,
1643
1591
  key: id,
1644
1592
  value: serializedRecord
1645
1593
  });
1646
- const scoreFromDb = await this.getScoreById({ id: score.id });
1647
- return { score: scoreFromDb };
1594
+ return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1648
1595
  } catch (error$1) {
1649
1596
  const mastraError = new error.MastraError(
1650
1597
  {
1651
- id: "CLOUDFLARE_STORAGE_SCORES_SAVE_SCORE_FAILED",
1598
+ id: storage.createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "FAILED"),
1652
1599
  domain: error.ErrorDomain.STORAGE,
1653
1600
  category: error.ErrorCategory.THIRD_PARTY,
1654
- text: `Failed to save score: ${score.id}`
1601
+ details: { id }
1655
1602
  },
1656
1603
  error$1
1657
1604
  );
@@ -1660,7 +1607,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1660
1607
  throw mastraError;
1661
1608
  }
1662
1609
  }
1663
- async getScoresByScorerId({
1610
+ async listScoresByScorerId({
1664
1611
  scorerId,
1665
1612
  entityId,
1666
1613
  entityType,
@@ -1690,15 +1637,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1690
1637
  const dateB = new Date(b.createdAt || 0).getTime();
1691
1638
  return dateB - dateA;
1692
1639
  });
1640
+ const { page, perPage: perPageInput } = pagination;
1641
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1642
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1693
1643
  const total = scores.length;
1694
- const start = pagination.page * pagination.perPage;
1695
- const end = start + pagination.perPage;
1644
+ const end = perPageInput === false ? scores.length : start + perPage;
1696
1645
  const pagedScores = scores.slice(start, end);
1697
1646
  return {
1698
1647
  pagination: {
1699
1648
  total,
1700
- page: pagination.page,
1701
- perPage: pagination.perPage,
1649
+ page,
1650
+ perPage: perPageForResponse,
1702
1651
  hasMore: end < total
1703
1652
  },
1704
1653
  scores: pagedScores
@@ -1706,7 +1655,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1706
1655
  } catch (error$1) {
1707
1656
  const mastraError = new error.MastraError(
1708
1657
  {
1709
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1658
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1710
1659
  domain: error.ErrorDomain.STORAGE,
1711
1660
  category: error.ErrorCategory.THIRD_PARTY,
1712
1661
  text: `Failed to get scores by scorer id: ${scorerId}`
@@ -1718,7 +1667,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1718
1667
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1719
1668
  }
1720
1669
  }
1721
- async getScoresByRunId({
1670
+ async listScoresByRunId({
1722
1671
  runId,
1723
1672
  pagination
1724
1673
  }) {
@@ -1736,15 +1685,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1736
1685
  const dateB = new Date(b.createdAt || 0).getTime();
1737
1686
  return dateB - dateA;
1738
1687
  });
1688
+ const { page, perPage: perPageInput } = pagination;
1689
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1690
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1739
1691
  const total = scores.length;
1740
- const start = pagination.page * pagination.perPage;
1741
- const end = start + pagination.perPage;
1692
+ const end = perPageInput === false ? scores.length : start + perPage;
1742
1693
  const pagedScores = scores.slice(start, end);
1743
1694
  return {
1744
1695
  pagination: {
1745
1696
  total,
1746
- page: pagination.page,
1747
- perPage: pagination.perPage,
1697
+ page,
1698
+ perPage: perPageForResponse,
1748
1699
  hasMore: end < total
1749
1700
  },
1750
1701
  scores: pagedScores
@@ -1752,7 +1703,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1752
1703
  } catch (error$1) {
1753
1704
  const mastraError = new error.MastraError(
1754
1705
  {
1755
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1706
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_RUN_ID", "FAILED"),
1756
1707
  domain: error.ErrorDomain.STORAGE,
1757
1708
  category: error.ErrorCategory.THIRD_PARTY,
1758
1709
  text: `Failed to get scores by run id: ${runId}`
@@ -1764,7 +1715,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1764
1715
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1765
1716
  }
1766
1717
  }
1767
- async getScoresByEntityId({
1718
+ async listScoresByEntityId({
1768
1719
  entityId,
1769
1720
  entityType,
1770
1721
  pagination
@@ -1783,15 +1734,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1783
1734
  const dateB = new Date(b.createdAt || 0).getTime();
1784
1735
  return dateB - dateA;
1785
1736
  });
1737
+ const { page, perPage: perPageInput } = pagination;
1738
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1739
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1786
1740
  const total = scores.length;
1787
- const start = pagination.page * pagination.perPage;
1788
- const end = start + pagination.perPage;
1741
+ const end = perPageInput === false ? scores.length : start + perPage;
1789
1742
  const pagedScores = scores.slice(start, end);
1790
1743
  return {
1791
1744
  pagination: {
1792
1745
  total,
1793
- page: pagination.page,
1794
- perPage: pagination.perPage,
1746
+ page,
1747
+ perPage: perPageForResponse,
1795
1748
  hasMore: end < total
1796
1749
  },
1797
1750
  scores: pagedScores
@@ -1799,7 +1752,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1799
1752
  } catch (error$1) {
1800
1753
  const mastraError = new error.MastraError(
1801
1754
  {
1802
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1755
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1803
1756
  domain: error.ErrorDomain.STORAGE,
1804
1757
  category: error.ErrorCategory.THIRD_PARTY,
1805
1758
  text: `Failed to get scores by entity id: ${entityId}, type: ${entityType}`
@@ -1811,126 +1764,55 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1811
1764
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1812
1765
  }
1813
1766
  }
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) {
1767
+ async listScoresBySpan({
1768
+ traceId,
1769
+ spanId,
1770
+ pagination
1771
+ }) {
1854
1772
  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 });
1773
+ const keys = await this.operations.listKV(storage.TABLE_SCORERS);
1774
+ const scores = [];
1775
+ for (const { name: key } of keys) {
1776
+ const score = await this.operations.getKV(storage.TABLE_SCORERS, key);
1777
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1778
+ scores.push(transformScoreRow(score));
1894
1779
  }
1895
1780
  }
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;
1781
+ scores.sort((a, b) => {
1782
+ const dateA = new Date(a.createdAt || 0).getTime();
1783
+ const dateB = new Date(b.createdAt || 0).getTime();
1784
+ return dateB - dateA;
1900
1785
  });
1901
- const total = traces.length;
1902
- const start = page * perPage;
1903
- const end = start + perPage;
1904
- const pagedTraces = traces.slice(start, end);
1786
+ const { page, perPage: perPageInput } = pagination;
1787
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1788
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1789
+ const total = scores.length;
1790
+ const end = perPageInput === false ? scores.length : start + perPage;
1791
+ const pagedScores = scores.slice(start, end);
1905
1792
  return {
1906
- traces: pagedTraces,
1907
- total,
1908
- page,
1909
- perPage,
1910
- hasMore: end < total
1793
+ pagination: {
1794
+ total,
1795
+ page,
1796
+ perPage: perPageForResponse,
1797
+ hasMore: end < total
1798
+ },
1799
+ scores: pagedScores
1911
1800
  };
1912
1801
  } catch (error$1) {
1913
1802
  const mastraError = new error.MastraError(
1914
1803
  {
1915
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1804
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SPAN", "FAILED"),
1916
1805
  domain: error.ErrorDomain.STORAGE,
1917
1806
  category: error.ErrorCategory.THIRD_PARTY,
1918
- text: "Error getting traces with pagination"
1807
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1919
1808
  },
1920
1809
  error$1
1921
1810
  );
1922
- this.logger.trackException?.(mastraError);
1923
- this.logger.error(mastraError.toString());
1924
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1811
+ this.logger?.trackException(mastraError);
1812
+ this.logger?.error(mastraError.toString());
1813
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1925
1814
  }
1926
1815
  }
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
1816
  };
1935
1817
  var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1936
1818
  operations;
@@ -1949,7 +1831,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1949
1831
  // runId,
1950
1832
  // stepId,
1951
1833
  // result,
1952
- // runtimeContext,
1834
+ // requestContext,
1953
1835
  }) {
1954
1836
  throw new Error("Method not implemented.");
1955
1837
  }
@@ -1970,7 +1852,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1970
1852
  workflow_name: workflowName,
1971
1853
  run_id: runId,
1972
1854
  resourceId,
1973
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1855
+ snapshot: JSON.stringify(snapshot),
1974
1856
  createdAt: /* @__PURE__ */ new Date(),
1975
1857
  updatedAt: /* @__PURE__ */ new Date()
1976
1858
  }
@@ -1978,7 +1860,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1978
1860
  } catch (error$1) {
1979
1861
  throw new error.MastraError(
1980
1862
  {
1981
- id: "CLOUDFLARE_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1863
+ id: storage.createStorageErrorId("CLOUDFLARE", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1982
1864
  domain: error.ErrorDomain.STORAGE,
1983
1865
  category: error.ErrorCategory.THIRD_PARTY,
1984
1866
  text: `Error persisting workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
@@ -2003,7 +1885,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2003
1885
  } catch (error$1) {
2004
1886
  const mastraError = new error.MastraError(
2005
1887
  {
2006
- id: "CLOUDFLARE_STORAGE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1888
+ id: storage.createStorageErrorId("CLOUDFLARE", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2007
1889
  domain: error.ErrorDomain.STORAGE,
2008
1890
  category: error.ErrorCategory.THIRD_PARTY,
2009
1891
  text: `Error loading workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
@@ -2049,15 +1931,29 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2049
1931
  if (resourceId) key += `:${resourceId}`;
2050
1932
  return key;
2051
1933
  }
2052
- async getWorkflowRuns({
1934
+ async listWorkflowRuns({
2053
1935
  workflowName,
2054
- limit = 20,
2055
- offset = 0,
1936
+ page = 0,
1937
+ perPage = 20,
2056
1938
  resourceId,
2057
1939
  fromDate,
2058
- toDate
1940
+ toDate,
1941
+ status
2059
1942
  } = {}) {
2060
1943
  try {
1944
+ if (page < 0 || !Number.isInteger(page)) {
1945
+ throw new error.MastraError(
1946
+ {
1947
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
1948
+ domain: error.ErrorDomain.STORAGE,
1949
+ category: error.ErrorCategory.USER,
1950
+ details: { page }
1951
+ },
1952
+ new Error("page must be a non-negative integer")
1953
+ );
1954
+ }
1955
+ const normalizedPerPage = storage.normalizePerPage(perPage, 20);
1956
+ const offset = page * normalizedPerPage;
2061
1957
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2062
1958
  const keyObjs = await this.operations.listKV(storage.TABLE_WORKFLOW_SNAPSHOT, { prefix });
2063
1959
  const runs = [];
@@ -2073,10 +1969,11 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2073
1969
  if (!data) continue;
2074
1970
  try {
2075
1971
  if (resourceId && !keyResourceId) continue;
1972
+ const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
1973
+ if (status && snapshotData.status !== status) continue;
2076
1974
  const createdAt = storage.ensureDate(data.createdAt);
2077
1975
  if (fromDate && createdAt && createdAt < fromDate) continue;
2078
1976
  if (toDate && createdAt && createdAt > toDate) continue;
2079
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2080
1977
  const resourceIdToUse = keyResourceId || data.resourceId;
2081
1978
  const run = this.parseWorkflowRun({
2082
1979
  ...data,
@@ -2094,7 +1991,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2094
1991
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2095
1992
  return bDate - aDate;
2096
1993
  });
2097
- const pagedRuns = runs.slice(offset, offset + limit);
1994
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2098
1995
  return {
2099
1996
  runs: pagedRuns,
2100
1997
  total: runs.length
@@ -2102,7 +1999,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2102
1999
  } catch (error$1) {
2103
2000
  const mastraError = new error.MastraError(
2104
2001
  {
2105
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
2002
+ id: storage.createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "FAILED"),
2106
2003
  domain: error.ErrorDomain.STORAGE,
2107
2004
  category: error.ErrorCategory.THIRD_PARTY
2108
2005
  },
@@ -2140,7 +2037,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2140
2037
  } catch (error$1) {
2141
2038
  const mastraError = new error.MastraError(
2142
2039
  {
2143
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2040
+ id: storage.createStorageErrorId("CLOUDFLARE", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2144
2041
  domain: error.ErrorDomain.STORAGE,
2145
2042
  category: error.ErrorCategory.THIRD_PARTY,
2146
2043
  details: {
@@ -2155,6 +2052,28 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2155
2052
  return null;
2156
2053
  }
2157
2054
  }
2055
+ async deleteWorkflowRunById({ runId, workflowName }) {
2056
+ try {
2057
+ if (!runId || !workflowName) {
2058
+ throw new Error("runId and workflowName are required");
2059
+ }
2060
+ const key = this.operations.getKey(storage.TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
2061
+ await this.operations.deleteKV(storage.TABLE_WORKFLOW_SNAPSHOT, key);
2062
+ } catch (error$1) {
2063
+ throw new error.MastraError(
2064
+ {
2065
+ id: storage.createStorageErrorId("CLOUDFLARE", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2066
+ domain: error.ErrorDomain.STORAGE,
2067
+ category: error.ErrorCategory.THIRD_PARTY,
2068
+ details: {
2069
+ workflowName,
2070
+ runId
2071
+ }
2072
+ },
2073
+ error$1
2074
+ );
2075
+ }
2076
+ }
2158
2077
  };
2159
2078
 
2160
2079
  // src/storage/types.ts
@@ -2176,14 +2095,7 @@ var CloudflareStore = class extends storage.MastraStorage {
2176
2095
  if (!config.bindings) {
2177
2096
  throw new Error("KV bindings are required when using Workers Binding API");
2178
2097
  }
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
- ];
2098
+ const requiredTables = [storage.TABLE_THREADS, storage.TABLE_MESSAGES, storage.TABLE_WORKFLOW_SNAPSHOT, storage.TABLE_SCORERS];
2187
2099
  for (const table of requiredTables) {
2188
2100
  if (!(table in config.bindings)) {
2189
2101
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2201,8 +2113,15 @@ var CloudflareStore = class extends storage.MastraStorage {
2201
2113
  throw new Error("apiToken is required for REST API");
2202
2114
  }
2203
2115
  }
2116
+ get supports() {
2117
+ const supports = super.supports;
2118
+ supports.listScoresBySpan = true;
2119
+ supports.resourceWorkingMemory = true;
2120
+ supports.selectByIncludeResourceScope = true;
2121
+ return supports;
2122
+ }
2204
2123
  constructor(config) {
2205
- super({ name: "Cloudflare" });
2124
+ super({ id: config.id, name: "Cloudflare", disableInit: config.disableInit });
2206
2125
  try {
2207
2126
  if (isWorkersConfig(config)) {
2208
2127
  this.validateWorkersConfig(config);
@@ -2224,15 +2143,9 @@ var CloudflareStore = class extends storage.MastraStorage {
2224
2143
  namespacePrefix: this.namespacePrefix,
2225
2144
  bindings: this.bindings
2226
2145
  });
2227
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2228
- operations
2229
- });
2230
2146
  const workflows = new WorkflowsStorageCloudflare({
2231
2147
  operations
2232
2148
  });
2233
- const traces = new TracesStorageCloudflare({
2234
- operations
2235
- });
2236
2149
  const memory = new MemoryStorageCloudflare({
2237
2150
  operations
2238
2151
  });
@@ -2241,16 +2154,14 @@ var CloudflareStore = class extends storage.MastraStorage {
2241
2154
  });
2242
2155
  this.stores = {
2243
2156
  operations,
2244
- legacyEvals,
2245
2157
  workflows,
2246
- traces,
2247
2158
  memory,
2248
2159
  scores
2249
2160
  };
2250
2161
  } catch (error$1) {
2251
2162
  throw new error.MastraError(
2252
2163
  {
2253
- id: "CLOUDFLARE_STORAGE_INIT_FAILED",
2164
+ id: storage.createStorageErrorId("CLOUDFLARE", "INIT", "FAILED"),
2254
2165
  domain: error.ErrorDomain.STORAGE,
2255
2166
  category: error.ErrorCategory.THIRD_PARTY
2256
2167
  },
@@ -2285,9 +2196,6 @@ var CloudflareStore = class extends storage.MastraStorage {
2285
2196
  async getThreadById({ threadId }) {
2286
2197
  return this.stores.memory.getThreadById({ threadId });
2287
2198
  }
2288
- async getThreadsByResourceId({ resourceId }) {
2289
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2290
- }
2291
2199
  async saveThread({ thread }) {
2292
2200
  return this.stores.memory.saveThread({ thread });
2293
2201
  }
@@ -2304,22 +2212,14 @@ var CloudflareStore = class extends storage.MastraStorage {
2304
2212
  async saveMessages(args) {
2305
2213
  return this.stores.memory.saveMessages(args);
2306
2214
  }
2307
- async getMessages({
2308
- threadId,
2309
- resourceId,
2310
- selectBy,
2311
- format
2312
- }) {
2313
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2314
- }
2315
2215
  async updateWorkflowResults({
2316
2216
  workflowName,
2317
2217
  runId,
2318
2218
  stepId,
2319
2219
  result,
2320
- runtimeContext
2220
+ requestContext
2321
2221
  }) {
2322
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2222
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2323
2223
  }
2324
2224
  async updateWorkflowState({
2325
2225
  workflowName,
@@ -2328,11 +2228,8 @@ var CloudflareStore = class extends storage.MastraStorage {
2328
2228
  }) {
2329
2229
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2330
2230
  }
2331
- async getMessagesById({
2332
- messageIds,
2333
- format
2334
- }) {
2335
- return this.stores.memory.getMessagesById({ messageIds, format });
2231
+ async listMessagesById({ messageIds }) {
2232
+ return this.stores.memory.listMessagesById({ messageIds });
2336
2233
  }
2337
2234
  async persistWorkflowSnapshot(params) {
2338
2235
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2343,46 +2240,23 @@ var CloudflareStore = class extends storage.MastraStorage {
2343
2240
  async batchInsert(input) {
2344
2241
  return this.stores.operations.batchInsert(input);
2345
2242
  }
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({
2243
+ async listWorkflowRuns({
2372
2244
  workflowName,
2373
- limit = 20,
2374
- offset = 0,
2245
+ perPage = 20,
2246
+ page = 0,
2375
2247
  resourceId,
2376
2248
  fromDate,
2377
- toDate
2249
+ toDate,
2250
+ status
2378
2251
  } = {}) {
2379
- return this.stores.workflows.getWorkflowRuns({
2252
+ return this.stores.workflows.listWorkflowRuns({
2380
2253
  workflowName,
2381
- limit,
2382
- offset,
2254
+ perPage,
2255
+ page,
2383
2256
  resourceId,
2384
2257
  fromDate,
2385
- toDate
2258
+ toDate,
2259
+ status
2386
2260
  });
2387
2261
  }
2388
2262
  async getWorkflowRunById({
@@ -2391,14 +2265,8 @@ var CloudflareStore = class extends storage.MastraStorage {
2391
2265
  }) {
2392
2266
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2393
2267
  }
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);
2268
+ async deleteWorkflowRunById({ runId, workflowName }) {
2269
+ return this.stores.workflows.deleteWorkflowRunById({ runId, workflowName });
2402
2270
  }
2403
2271
  async updateMessages(args) {
2404
2272
  return this.stores.memory.updateMessages(args);
@@ -2409,27 +2277,34 @@ var CloudflareStore = class extends storage.MastraStorage {
2409
2277
  async saveScore(score) {
2410
2278
  return this.stores.scores.saveScore(score);
2411
2279
  }
2412
- async getScoresByRunId({
2280
+ async listScoresByRunId({
2413
2281
  runId,
2414
2282
  pagination
2415
2283
  }) {
2416
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2284
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2417
2285
  }
2418
- async getScoresByEntityId({
2286
+ async listScoresByEntityId({
2419
2287
  entityId,
2420
2288
  entityType,
2421
2289
  pagination
2422
2290
  }) {
2423
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2291
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2424
2292
  }
2425
- async getScoresByScorerId({
2293
+ async listScoresByScorerId({
2426
2294
  scorerId,
2427
2295
  entityId,
2428
2296
  entityType,
2429
2297
  source,
2430
2298
  pagination
2431
2299
  }) {
2432
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2300
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2301
+ }
2302
+ async listScoresBySpan({
2303
+ traceId,
2304
+ spanId,
2305
+ pagination
2306
+ }) {
2307
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2433
2308
  }
2434
2309
  async getResourceById({ resourceId }) {
2435
2310
  return this.stores.memory.getResourceById({ resourceId });