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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,109 +1,10 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_SCORERS, TABLE_TRACES, StoreOperations, serializeDate, ensureDate, LegacyEvalsStorage, WorkflowsStorage, TracesStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage, safelyParseJSON } from '@mastra/core/storage';
2
+ import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCORERS, createStorageErrorId, StoreOperations, TABLE_TRACES, WorkflowsStorage, ensureDate, normalizePerPage, MemoryStorage, calculatePagination, serializeDate, TABLE_RESOURCES, ScoresStorage, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { MessageList } from '@mastra/core/agent';
5
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
5
6
 
6
7
  // src/storage/index.ts
7
- var LegacyEvalsStorageCloudflare = class extends LegacyEvalsStorage {
8
- operations;
9
- constructor({ operations }) {
10
- super();
11
- this.operations = operations;
12
- }
13
- async getEvalsByAgentName(agentName, type) {
14
- try {
15
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
16
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
17
- const evals = [];
18
- for (const { name: key } of keyObjs) {
19
- const data = await this.operations.getKV(TABLE_EVALS, key);
20
- if (!data) continue;
21
- if (data.agent_name !== agentName) continue;
22
- if (type) {
23
- const isTest = data.test_info !== null && data.test_info !== void 0;
24
- const evalType = isTest ? "test" : "live";
25
- if (evalType !== type) continue;
26
- }
27
- const mappedData = {
28
- ...data,
29
- runId: data.run_id,
30
- testInfo: data.test_info
31
- };
32
- evals.push(mappedData);
33
- }
34
- evals.sort((a, b) => {
35
- const aTime = new Date(a.createdAt || 0).getTime();
36
- const bTime = new Date(b.createdAt || 0).getTime();
37
- return bTime - aTime;
38
- });
39
- return evals;
40
- } catch (error) {
41
- throw new MastraError(
42
- {
43
- id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
44
- domain: ErrorDomain.STORAGE,
45
- category: ErrorCategory.THIRD_PARTY,
46
- text: "Failed to get evals by agent name"
47
- },
48
- error
49
- );
50
- }
51
- }
52
- async getEvals(options) {
53
- try {
54
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
55
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
56
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
57
- const evals = [];
58
- for (const { name: key } of keyObjs) {
59
- const data = await this.operations.getKV(TABLE_EVALS, key);
60
- if (!data) continue;
61
- if (agentName && data.agent_name !== agentName) continue;
62
- if (type) {
63
- const isTest = data.test_info !== null && data.test_info !== void 0;
64
- const evalType = isTest ? "test" : "live";
65
- if (evalType !== type) continue;
66
- }
67
- if (dateRange?.start || dateRange?.end) {
68
- const evalDate = new Date(data.createdAt || data.created_at || 0);
69
- if (dateRange.start && evalDate < dateRange.start) continue;
70
- if (dateRange.end && evalDate > dateRange.end) continue;
71
- }
72
- const mappedData = {
73
- ...data,
74
- runId: data.run_id,
75
- testInfo: data.test_info
76
- };
77
- evals.push(mappedData);
78
- }
79
- evals.sort((a, b) => {
80
- const aTime = new Date(a.createdAt || 0).getTime();
81
- const bTime = new Date(b.createdAt || 0).getTime();
82
- return bTime - aTime;
83
- });
84
- const start = page * perPage;
85
- const end = start + perPage;
86
- const paginatedEvals = evals.slice(start, end);
87
- return {
88
- page,
89
- perPage,
90
- total: evals.length,
91
- hasMore: start + perPage < evals.length,
92
- evals: paginatedEvals
93
- };
94
- } catch (error) {
95
- throw new MastraError(
96
- {
97
- id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
98
- domain: ErrorDomain.STORAGE,
99
- category: ErrorCategory.THIRD_PARTY,
100
- text: "Failed to get evals"
101
- },
102
- error
103
- );
104
- }
105
- }
106
- };
107
8
  var MemoryStorageCloudflare = class extends MemoryStorage {
108
9
  operations;
109
10
  constructor({ operations }) {
@@ -114,6 +15,17 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
114
15
  if (!metadata) return void 0;
115
16
  return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
116
17
  }
18
+ /**
19
+ * Summarizes message content without exposing raw data (for logging).
20
+ * Returns type, length, and keys only to prevent PII leakage.
21
+ */
22
+ summarizeMessageContent(content) {
23
+ if (!content) return { type: "undefined" };
24
+ if (typeof content === "string") return { type: "string", length: content.length };
25
+ if (Array.isArray(content)) return { type: "array", length: content.length };
26
+ if (typeof content === "object") return { type: "object", keys: Object.keys(content) };
27
+ return { type: typeof content };
28
+ }
117
29
  async getThreadById({ threadId }) {
118
30
  const thread = await this.operations.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
119
31
  if (!thread) return null;
@@ -127,7 +39,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
127
39
  } catch (error) {
128
40
  const mastraError = new MastraError(
129
41
  {
130
- id: "CLOUDFLARE_STORAGE_GET_THREAD_BY_ID_FAILED",
42
+ id: createStorageErrorId("CLOUDFLARE", "GET_THREAD_BY_ID", "FAILED"),
131
43
  domain: ErrorDomain.STORAGE,
132
44
  category: ErrorCategory.THIRD_PARTY,
133
45
  details: {
@@ -141,61 +53,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
141
53
  return null;
142
54
  }
143
55
  }
144
- async getThreadsByResourceId({ resourceId }) {
145
- try {
146
- const keyList = await this.operations.listKV(TABLE_THREADS);
147
- const threads = await Promise.all(
148
- keyList.map(async (keyObj) => {
149
- try {
150
- const data = await this.operations.getKV(TABLE_THREADS, keyObj.name);
151
- if (!data) return null;
152
- const thread = typeof data === "string" ? JSON.parse(data) : data;
153
- if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
154
- return {
155
- ...thread,
156
- createdAt: ensureDate(thread.createdAt),
157
- updatedAt: ensureDate(thread.updatedAt),
158
- metadata: this.ensureMetadata(thread.metadata)
159
- };
160
- } catch (error) {
161
- const mastraError = new MastraError(
162
- {
163
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
164
- domain: ErrorDomain.STORAGE,
165
- category: ErrorCategory.THIRD_PARTY,
166
- details: {
167
- resourceId
168
- }
169
- },
170
- error
171
- );
172
- this.logger?.trackException(mastraError);
173
- this.logger?.error(mastraError.toString());
174
- return null;
175
- }
176
- })
177
- );
178
- return threads.filter((thread) => thread !== null);
179
- } catch (error) {
180
- const mastraError = new MastraError(
181
- {
182
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
183
- domain: ErrorDomain.STORAGE,
184
- category: ErrorCategory.THIRD_PARTY,
185
- details: {
186
- resourceId
187
- }
188
- },
189
- error
190
- );
191
- this.logger?.trackException(mastraError);
192
- this.logger?.error(mastraError.toString());
193
- return [];
194
- }
195
- }
196
- async getThreadsByResourceIdPaginated(args) {
56
+ async listThreadsByResourceId(args) {
197
57
  try {
198
- const { resourceId, page = 0, perPage = 100 } = args;
58
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
59
+ const perPage = normalizePerPage(perPageInput, 100);
60
+ if (page < 0) {
61
+ throw new MastraError(
62
+ {
63
+ id: createStorageErrorId("CLOUDFLARE", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
64
+ domain: ErrorDomain.STORAGE,
65
+ category: ErrorCategory.USER,
66
+ details: { page }
67
+ },
68
+ new Error("page must be >= 0")
69
+ );
70
+ }
71
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
72
+ const { field, direction } = this.parseOrderBy(orderBy);
199
73
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
200
74
  const keyObjs = await this.operations.listKV(TABLE_THREADS, { prefix: `${prefix}${TABLE_THREADS}` });
201
75
  const threads = [];
@@ -206,24 +80,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
206
80
  threads.push(data);
207
81
  }
208
82
  threads.sort((a, b) => {
209
- const aTime = new Date(a.createdAt || 0).getTime();
210
- const bTime = new Date(b.createdAt || 0).getTime();
211
- return bTime - aTime;
83
+ const aTime = new Date(a[field] || 0).getTime();
84
+ const bTime = new Date(b[field] || 0).getTime();
85
+ return direction === "ASC" ? aTime - bTime : bTime - aTime;
212
86
  });
213
- const start = page * perPage;
214
- const end = start + perPage;
215
- const paginatedThreads = threads.slice(start, end);
87
+ const end = perPageInput === false ? threads.length : offset + perPage;
88
+ const paginatedThreads = threads.slice(offset, end);
216
89
  return {
217
90
  page,
218
- perPage,
91
+ perPage: perPageForResponse,
219
92
  total: threads.length,
220
- hasMore: start + perPage < threads.length,
93
+ hasMore: perPageInput === false ? false : offset + perPage < threads.length,
221
94
  threads: paginatedThreads
222
95
  };
223
96
  } catch (error) {
224
97
  throw new MastraError(
225
98
  {
226
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
99
+ id: createStorageErrorId("CLOUDFLARE", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
227
100
  domain: ErrorDomain.STORAGE,
228
101
  category: ErrorCategory.THIRD_PARTY,
229
102
  text: "Failed to get threads by resource ID with pagination"
@@ -239,7 +112,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
239
112
  } catch (error) {
240
113
  throw new MastraError(
241
114
  {
242
- id: "CLOUDFLARE_STORAGE_SAVE_THREAD_FAILED",
115
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_THREAD", "FAILED"),
243
116
  domain: ErrorDomain.STORAGE,
244
117
  category: ErrorCategory.THIRD_PARTY,
245
118
  details: {
@@ -274,7 +147,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
274
147
  } catch (error) {
275
148
  throw new MastraError(
276
149
  {
277
- id: "CLOUDFLARE_STORAGE_UPDATE_THREAD_FAILED",
150
+ id: createStorageErrorId("CLOUDFLARE", "UPDATE_THREAD", "FAILED"),
278
151
  domain: ErrorDomain.STORAGE,
279
152
  category: ErrorCategory.THIRD_PARTY,
280
153
  details: {
@@ -291,7 +164,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
291
164
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: messageId });
292
165
  } catch (error) {
293
166
  const message = error instanceof Error ? error.message : String(error);
294
- this.logger.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
167
+ this.logger?.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
295
168
  throw error;
296
169
  }
297
170
  }
@@ -300,7 +173,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
300
173
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: "messages" });
301
174
  } catch (error) {
302
175
  const message = error instanceof Error ? error.message : String(error);
303
- this.logger.error(`Error getting thread messages key for thread ${threadId}:`, { message });
176
+ this.logger?.error(`Error getting thread messages key for thread ${threadId}:`, { message });
304
177
  throw error;
305
178
  }
306
179
  }
@@ -323,7 +196,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
323
196
  } catch (error) {
324
197
  throw new MastraError(
325
198
  {
326
- id: "CLOUDFLARE_STORAGE_DELETE_THREAD_FAILED",
199
+ id: createStorageErrorId("CLOUDFLARE", "DELETE_THREAD", "FAILED"),
327
200
  domain: ErrorDomain.STORAGE,
328
201
  category: ErrorCategory.THIRD_PARTY,
329
202
  details: {
@@ -334,6 +207,17 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
334
207
  );
335
208
  }
336
209
  }
210
+ /**
211
+ * Searches all threads in the KV store to find a message by its ID.
212
+ *
213
+ * **Performance Warning**: This method sequentially scans all threads to locate
214
+ * the message. For stores with many threads, this can result in significant
215
+ * latency and API calls. When possible, callers should provide the `threadId`
216
+ * directly to avoid this full scan.
217
+ *
218
+ * @param messageId - The globally unique message ID to search for
219
+ * @returns The message with its threadId if found, null otherwise
220
+ */
337
221
  async findMessageInAnyThread(messageId) {
338
222
  try {
339
223
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
@@ -390,7 +274,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
390
274
  });
391
275
  } catch (error) {
392
276
  const message = error instanceof Error ? error.message : String(error);
393
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
277
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
394
278
  throw error;
395
279
  } finally {
396
280
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -408,7 +292,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
408
292
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
409
293
  return Array.isArray(arr) ? arr : [];
410
294
  } catch (e) {
411
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
295
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
412
296
  return [];
413
297
  }
414
298
  }
@@ -439,8 +323,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
439
323
  }
440
324
  }
441
325
  async saveMessages(args) {
442
- const { messages, format = "v1" } = args;
443
- if (!Array.isArray(messages) || messages.length === 0) return [];
326
+ const { messages } = args;
327
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
444
328
  try {
445
329
  const validatedMessages = messages.map((message, index) => {
446
330
  const errors = [];
@@ -463,9 +347,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
463
347
  const messageMigrationTasks = [];
464
348
  for (const message of validatedMessages) {
465
349
  const existingMessage = await this.findMessageInAnyThread(message.id);
466
- console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
350
+ this.logger?.debug(
351
+ `Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`
352
+ );
467
353
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
468
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
354
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
469
355
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
470
356
  }
471
357
  }
@@ -494,10 +380,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
494
380
  ...cleanMessage,
495
381
  createdAt: serializeDate(cleanMessage.createdAt)
496
382
  };
497
- console.log(`Saving message ${message.id} with content:`, {
498
- content: serializedMessage.content,
499
- contentType: typeof serializedMessage.content,
500
- isArray: Array.isArray(serializedMessage.content)
383
+ this.logger?.debug(`Saving message ${message.id}`, {
384
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
501
385
  });
502
386
  await this.operations.putKV({ tableName: TABLE_MESSAGES, key, value: serializedMessage });
503
387
  })
@@ -517,7 +401,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
517
401
  } catch (error) {
518
402
  throw new MastraError(
519
403
  {
520
- id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
404
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
521
405
  domain: ErrorDomain.STORAGE,
522
406
  category: ErrorCategory.THIRD_PARTY,
523
407
  details: {
@@ -533,12 +417,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
533
417
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
534
418
  );
535
419
  const list = new MessageList().add(prepared, "memory");
536
- if (format === `v2`) return list.get.all.v2();
537
- return list.get.all.v1();
420
+ return { messages: list.get.all.db() };
538
421
  } catch (error) {
539
422
  throw new MastraError(
540
423
  {
541
- id: "CLOUDFLARE_STORAGE_SAVE_MESSAGES_FAILED",
424
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_MESSAGES", "FAILED"),
542
425
  domain: ErrorDomain.STORAGE,
543
426
  category: ErrorCategory.THIRD_PARTY
544
427
  },
@@ -564,10 +447,25 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
564
447
  async getFullOrder(orderKey) {
565
448
  return this.getRange(orderKey, 0, -1);
566
449
  }
567
- async getIncludedMessagesWithContext(threadId, include, messageIds) {
450
+ /**
451
+ * Retrieves messages specified in the include array along with their surrounding context.
452
+ *
453
+ * **Performance Note**: When `threadId` is not provided in an include entry, this method
454
+ * must call `findMessageInAnyThread` which sequentially scans all threads in the KV store.
455
+ * For optimal performance, callers should provide `threadId` in include entries when known.
456
+ *
457
+ * @param include - Array of message IDs to include, optionally with context windows
458
+ * @param messageIds - Set to accumulate the message IDs that should be fetched
459
+ */
460
+ async getIncludedMessagesWithContext(include, messageIds) {
568
461
  await Promise.all(
569
462
  include.map(async (item) => {
570
- const targetThreadId = item.threadId || threadId;
463
+ let targetThreadId = item.threadId;
464
+ if (!targetThreadId) {
465
+ const foundMessage = await this.findMessageInAnyThread(item.id);
466
+ if (!foundMessage) return;
467
+ targetThreadId = foundMessage.threadId;
468
+ }
571
469
  if (!targetThreadId) return;
572
470
  const threadMessagesKey = this.getThreadMessagesKey(targetThreadId);
573
471
  messageIds.add(item.id);
@@ -597,9 +495,16 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
597
495
  const latestIds = await this.getLastN(threadMessagesKey, limit);
598
496
  latestIds.forEach((id) => messageIds.add(id));
599
497
  } catch {
600
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
498
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
601
499
  }
602
500
  }
501
+ /**
502
+ * Fetches and parses messages from one or more threads.
503
+ *
504
+ * **Performance Note**: When neither `include` entries with `threadId` nor `targetThreadId`
505
+ * are provided, this method falls back to `findMessageInAnyThread` which scans all threads.
506
+ * For optimal performance, provide `threadId` in include entries or specify `targetThreadId`.
507
+ */
603
508
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
604
509
  const messageIdToThreadId = /* @__PURE__ */ new Map();
605
510
  if (include) {
@@ -628,111 +533,29 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
628
533
  const data = await this.operations.getKV(TABLE_MESSAGES, key);
629
534
  if (!data) return null;
630
535
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
631
- console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
632
- content: parsed.content,
633
- contentType: typeof parsed.content,
634
- isArray: Array.isArray(parsed.content)
536
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
537
+ contentSummary: this.summarizeMessageContent(parsed.content)
635
538
  });
636
539
  return parsed;
637
540
  } catch (error) {
638
541
  const message = error instanceof Error ? error.message : String(error);
639
- this.logger.error(`Error retrieving message ${id}:`, { message });
542
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
640
543
  return null;
641
544
  }
642
545
  })
643
546
  );
644
547
  return messages.filter((msg) => msg !== null);
645
548
  }
646
- async getMessages({
647
- threadId,
648
- resourceId,
649
- selectBy,
650
- format
651
- }) {
652
- console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
653
- const actualFormat = format || "v1";
654
- console.log(`Using format: ${actualFormat}`);
655
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
656
- const messageIds = /* @__PURE__ */ new Set();
657
- if (limit === 0 && !selectBy?.include?.length) return [];
658
- try {
659
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
660
- await Promise.all([
661
- selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
662
- limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
663
- ]);
664
- const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
665
- const messages = await this.fetchAndParseMessagesFromMultipleThreads(
666
- Array.from(messageIds),
667
- selectBy?.include,
668
- targetThreadId
669
- );
670
- if (!messages.length) return [];
671
- try {
672
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
673
- const messageOrder = await this.getFullOrder(threadMessagesKey);
674
- const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
675
- messages.sort((a, b) => {
676
- const indexA = orderMap.get(a.id);
677
- const indexB = orderMap.get(b.id);
678
- if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
679
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
680
- });
681
- } catch (error) {
682
- const mastraError = new MastraError(
683
- {
684
- id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
685
- domain: ErrorDomain.STORAGE,
686
- category: ErrorCategory.THIRD_PARTY,
687
- text: `Error sorting messages for thread ${threadId} falling back to creation time`,
688
- details: {
689
- threadId
690
- }
691
- },
692
- error
693
- );
694
- this.logger?.trackException(mastraError);
695
- this.logger?.error(mastraError.toString());
696
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
697
- }
698
- const prepared = messages.map(({ _index, ...message }) => ({
699
- ...message,
700
- type: message.type === `v2` ? void 0 : message.type,
701
- createdAt: ensureDate(message.createdAt)
702
- }));
703
- if (actualFormat === `v1`) {
704
- console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
705
- return prepared.map((msg) => ({
706
- ...msg,
707
- createdAt: new Date(msg.createdAt)
708
- }));
709
- }
710
- const list = new MessageList({ threadId, resourceId }).add(prepared, "memory");
711
- return list.get.all.v2();
712
- } catch (error) {
713
- const mastraError = new MastraError(
714
- {
715
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
716
- domain: ErrorDomain.STORAGE,
717
- category: ErrorCategory.THIRD_PARTY,
718
- text: `Error retrieving messages for thread ${threadId}`,
719
- details: {
720
- threadId,
721
- resourceId: resourceId ?? ""
722
- }
723
- },
724
- error
725
- );
726
- this.logger?.trackException(mastraError);
727
- this.logger?.error(mastraError.toString());
728
- return [];
729
- }
730
- }
731
- async getMessagesById({
732
- messageIds,
733
- format
734
- }) {
735
- if (messageIds.length === 0) return [];
549
+ /**
550
+ * Retrieves messages by their IDs.
551
+ *
552
+ * **Performance Warning**: This method calls `findMessageInAnyThread` for each message ID,
553
+ * which scans all threads in the KV store. For large numbers of messages or threads,
554
+ * this can result in significant latency. Consider using `listMessages` with specific
555
+ * thread IDs when the thread context is known.
556
+ */
557
+ async listMessagesById({ messageIds }) {
558
+ if (messageIds.length === 0) return { messages: [] };
736
559
  try {
737
560
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
738
561
  (result) => !!result
@@ -743,12 +566,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
743
566
  createdAt: ensureDate(message.createdAt)
744
567
  }));
745
568
  const list = new MessageList().add(prepared, "memory");
746
- if (format === `v1`) return list.get.all.v1();
747
- return list.get.all.v2();
569
+ return { messages: list.get.all.db() };
748
570
  } catch (error) {
749
571
  const mastraError = new MastraError(
750
572
  {
751
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
573
+ id: createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES_BY_ID", "FAILED"),
752
574
  domain: ErrorDomain.STORAGE,
753
575
  category: ErrorCategory.THIRD_PARTY,
754
576
  text: `Error retrieving messages by ID`,
@@ -760,52 +582,198 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
760
582
  );
761
583
  this.logger?.trackException(mastraError);
762
584
  this.logger?.error(mastraError.toString());
763
- return [];
585
+ return { messages: [] };
764
586
  }
765
587
  }
766
- async getMessagesPaginated(args) {
767
- const { threadId, resourceId, selectBy, format = "v1" } = args;
768
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
588
+ async listMessages(args) {
589
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
590
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
591
+ const isValidThreadId = (id) => typeof id === "string" && id.trim().length > 0;
592
+ if (threadIds.length === 0 || threadIds.some((id) => !isValidThreadId(id))) {
593
+ throw new MastraError(
594
+ {
595
+ id: createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_THREAD_ID"),
596
+ domain: ErrorDomain.STORAGE,
597
+ category: ErrorCategory.THIRD_PARTY,
598
+ details: { threadId: Array.isArray(threadId) ? JSON.stringify(threadId) : String(threadId) }
599
+ },
600
+ new Error("threadId must be a non-empty string or array of non-empty strings")
601
+ );
602
+ }
603
+ const perPage = normalizePerPage(perPageInput, 40);
604
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
769
605
  try {
770
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
771
- const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
772
- let filteredMessages = messages;
773
- if (selectBy?.pagination?.dateRange) {
774
- const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
775
- filteredMessages = messages.filter((message) => {
776
- const messageDate = new Date(message.createdAt);
777
- if (dateStart && messageDate < dateStart) return false;
778
- if (dateEnd && messageDate > dateEnd) return false;
606
+ if (page < 0) {
607
+ throw new MastraError(
608
+ {
609
+ id: createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "INVALID_PAGE"),
610
+ domain: ErrorDomain.STORAGE,
611
+ category: ErrorCategory.USER,
612
+ details: { page }
613
+ },
614
+ new Error("page must be >= 0")
615
+ );
616
+ }
617
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
618
+ const threadMessageIds = /* @__PURE__ */ new Set();
619
+ for (const tid of threadIds) {
620
+ try {
621
+ const threadMessagesKey = this.getThreadMessagesKey(tid);
622
+ const allIds = await this.getFullOrder(threadMessagesKey);
623
+ allIds.forEach((id) => threadMessageIds.add(id));
624
+ } catch {
625
+ }
626
+ }
627
+ const threadMessages = await this.fetchAndParseMessagesFromMultipleThreads(
628
+ Array.from(threadMessageIds),
629
+ void 0,
630
+ threadIds.length === 1 ? threadIds[0] : void 0
631
+ );
632
+ let filteredThreadMessages = threadMessages;
633
+ if (resourceId) {
634
+ filteredThreadMessages = filteredThreadMessages.filter((msg) => msg.resourceId === resourceId);
635
+ }
636
+ const dateRange = filter?.dateRange;
637
+ if (dateRange) {
638
+ filteredThreadMessages = filteredThreadMessages.filter((msg) => {
639
+ const messageDate = new Date(msg.createdAt);
640
+ if (dateRange.start && messageDate < new Date(dateRange.start)) return false;
641
+ if (dateRange.end && messageDate > new Date(dateRange.end)) return false;
779
642
  return true;
780
643
  });
781
644
  }
782
- const start = page * perPage;
783
- const end = start + perPage;
784
- const paginatedMessages = filteredMessages.slice(start, end);
645
+ const total = filteredThreadMessages.length;
646
+ if (perPage === 0 && (!include || include.length === 0)) {
647
+ return {
648
+ messages: [],
649
+ total,
650
+ page,
651
+ perPage: perPageForResponse,
652
+ hasMore: offset < total
653
+ };
654
+ }
655
+ filteredThreadMessages.sort((a, b) => {
656
+ const timeA = new Date(a.createdAt).getTime();
657
+ const timeB = new Date(b.createdAt).getTime();
658
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
659
+ if (timeDiff === 0) {
660
+ return a.id.localeCompare(b.id);
661
+ }
662
+ return timeDiff;
663
+ });
664
+ let paginatedMessages;
665
+ if (perPage === 0) {
666
+ paginatedMessages = [];
667
+ } else if (perPage === Number.MAX_SAFE_INTEGER) {
668
+ paginatedMessages = filteredThreadMessages;
669
+ } else {
670
+ paginatedMessages = filteredThreadMessages.slice(offset, offset + perPage);
671
+ }
672
+ let includedMessages = [];
673
+ if (include && include.length > 0) {
674
+ const includedMessageIds = /* @__PURE__ */ new Set();
675
+ await this.getIncludedMessagesWithContext(include, includedMessageIds);
676
+ const paginatedIds = new Set(paginatedMessages.map((m) => m.id));
677
+ const idsToFetch = Array.from(includedMessageIds).filter((id) => !paginatedIds.has(id));
678
+ if (idsToFetch.length > 0) {
679
+ includedMessages = await this.fetchAndParseMessagesFromMultipleThreads(idsToFetch, include, void 0);
680
+ }
681
+ }
682
+ const seenIds = /* @__PURE__ */ new Set();
683
+ const allMessages = [];
684
+ for (const msg of paginatedMessages) {
685
+ if (!seenIds.has(msg.id)) {
686
+ allMessages.push(msg);
687
+ seenIds.add(msg.id);
688
+ }
689
+ }
690
+ for (const msg of includedMessages) {
691
+ if (!seenIds.has(msg.id)) {
692
+ allMessages.push(msg);
693
+ seenIds.add(msg.id);
694
+ }
695
+ }
696
+ allMessages.sort((a, b) => {
697
+ const timeA = new Date(a.createdAt).getTime();
698
+ const timeB = new Date(b.createdAt).getTime();
699
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
700
+ if (timeDiff === 0) {
701
+ return a.id.localeCompare(b.id);
702
+ }
703
+ return timeDiff;
704
+ });
705
+ let filteredMessages = allMessages;
706
+ const paginatedCount = paginatedMessages.length;
707
+ if (total === 0 && filteredMessages.length === 0 && (!include || include.length === 0)) {
708
+ return {
709
+ messages: [],
710
+ total: 0,
711
+ page,
712
+ perPage: perPageForResponse,
713
+ hasMore: false
714
+ };
715
+ }
716
+ const prepared = filteredMessages.map(({ _index, ...message }) => ({
717
+ ...message,
718
+ type: message.type !== "v2" ? message.type : void 0,
719
+ createdAt: ensureDate(message.createdAt)
720
+ }));
721
+ const primaryThreadId = Array.isArray(threadId) ? threadId[0] : threadId;
722
+ const list = new MessageList({ threadId: primaryThreadId, resourceId }).add(
723
+ prepared,
724
+ "memory"
725
+ );
726
+ let finalMessages = list.get.all.db();
727
+ finalMessages = finalMessages.sort((a, b) => {
728
+ const isDateField = field === "createdAt" || field === "updatedAt";
729
+ const aVal = isDateField ? new Date(a[field]).getTime() : a[field];
730
+ const bVal = isDateField ? new Date(b[field]).getTime() : b[field];
731
+ if (aVal == null && bVal == null) return a.id.localeCompare(b.id);
732
+ if (aVal == null) return 1;
733
+ if (bVal == null) return -1;
734
+ if (typeof aVal === "number" && typeof bVal === "number") {
735
+ const cmp2 = direction === "ASC" ? aVal - bVal : bVal - aVal;
736
+ return cmp2 !== 0 ? cmp2 : a.id.localeCompare(b.id);
737
+ }
738
+ const cmp = direction === "ASC" ? String(aVal).localeCompare(String(bVal)) : String(bVal).localeCompare(String(aVal));
739
+ return cmp !== 0 ? cmp : a.id.localeCompare(b.id);
740
+ });
741
+ const threadIdSet = new Set(threadIds);
742
+ const returnedThreadMessageIds = new Set(
743
+ finalMessages.filter((m) => m.threadId && threadIdSet.has(m.threadId)).map((m) => m.id)
744
+ );
745
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
746
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + paginatedCount < total;
785
747
  return {
748
+ messages: finalMessages,
749
+ total,
786
750
  page,
787
- perPage,
788
- total: filteredMessages.length,
789
- hasMore: start + perPage < filteredMessages.length,
790
- messages: paginatedMessages
751
+ perPage: perPageForResponse,
752
+ hasMore
791
753
  };
792
754
  } catch (error) {
793
755
  const mastraError = new MastraError(
794
756
  {
795
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
757
+ id: createStorageErrorId("CLOUDFLARE", "LIST_MESSAGES", "FAILED"),
796
758
  domain: ErrorDomain.STORAGE,
797
759
  category: ErrorCategory.THIRD_PARTY,
798
- text: "Failed to get messages with pagination",
760
+ text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error instanceof Error ? error.message : String(error)}`,
799
761
  details: {
800
- threadId,
762
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
801
763
  resourceId: resourceId ?? ""
802
764
  }
803
765
  },
804
766
  error
805
767
  );
806
- this.logger?.trackException?.(mastraError);
807
768
  this.logger?.error?.(mastraError.toString());
808
- return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
769
+ this.logger?.trackException?.(mastraError);
770
+ return {
771
+ messages: [],
772
+ total: 0,
773
+ page,
774
+ perPage: perPageForResponse,
775
+ hasMore: false
776
+ };
809
777
  }
810
778
  }
811
779
  async updateMessages(args) {
@@ -908,7 +876,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
908
876
  } catch (error) {
909
877
  throw new MastraError(
910
878
  {
911
- id: "CLOUDFLARE_STORAGE_UPDATE_MESSAGES_FAILED",
879
+ id: createStorageErrorId("CLOUDFLARE", "UPDATE_MESSAGES", "FAILED"),
912
880
  domain: ErrorDomain.STORAGE,
913
881
  category: ErrorCategory.THIRD_PARTY,
914
882
  text: "Failed to update messages"
@@ -931,7 +899,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
931
899
  } catch (error) {
932
900
  const mastraError = new MastraError(
933
901
  {
934
- id: "CLOUDFLARE_STORAGE_GET_RESOURCE_BY_ID_FAILED",
902
+ id: createStorageErrorId("CLOUDFLARE", "GET_RESOURCE_BY_ID", "FAILED"),
935
903
  domain: ErrorDomain.STORAGE,
936
904
  category: ErrorCategory.THIRD_PARTY,
937
905
  details: {
@@ -960,7 +928,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
960
928
  } catch (error) {
961
929
  throw new MastraError(
962
930
  {
963
- id: "CLOUDFLARE_STORAGE_SAVE_RESOURCE_FAILED",
931
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_RESOURCE", "FAILED"),
964
932
  domain: ErrorDomain.STORAGE,
965
933
  category: ErrorCategory.THIRD_PARTY,
966
934
  details: {
@@ -1031,7 +999,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1031
999
  } catch (error) {
1032
1000
  throw new MastraError(
1033
1001
  {
1034
- id: "CLOUDFLARE_STORAGE_CLEAR_TABLE_FAILED",
1002
+ id: createStorageErrorId("CLOUDFLARE", "CLEAR_TABLE", "FAILED"),
1035
1003
  domain: ErrorDomain.STORAGE,
1036
1004
  category: ErrorCategory.THIRD_PARTY,
1037
1005
  details: {
@@ -1051,7 +1019,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1051
1019
  } catch (error) {
1052
1020
  throw new MastraError(
1053
1021
  {
1054
- id: "CLOUDFLARE_STORAGE_DROP_TABLE_FAILED",
1022
+ id: createStorageErrorId("CLOUDFLARE", "DROP_TABLE", "FAILED"),
1055
1023
  domain: ErrorDomain.STORAGE,
1056
1024
  category: ErrorCategory.THIRD_PARTY,
1057
1025
  details: {
@@ -1091,10 +1059,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1091
1059
  case TABLE_TRACES:
1092
1060
  if (!record.id) throw new Error("Trace ID is required");
1093
1061
  return `${prefix}${tableName}:${record.id}`;
1094
- case TABLE_EVALS:
1095
- const evalId = record.id || record.run_id;
1096
- if (!evalId) throw new Error("Eval ID or run_id is required");
1097
- return `${prefix}${tableName}:${evalId}`;
1098
1062
  case TABLE_SCORERS:
1099
1063
  if (!record.id) throw new Error("Score ID is required");
1100
1064
  return `${prefix}${tableName}:${record.id}`;
@@ -1334,11 +1298,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1334
1298
  throw new Error("Trace record missing required fields");
1335
1299
  }
1336
1300
  break;
1337
- case TABLE_EVALS:
1338
- if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
1339
- throw new Error("Eval record missing required fields");
1340
- }
1341
- break;
1342
1301
  case TABLE_SCORERS:
1343
1302
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1344
1303
  throw new Error("Score record missing required fields");
@@ -1356,18 +1315,13 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1356
1315
  async insert({ tableName, record }) {
1357
1316
  try {
1358
1317
  const key = this.getKey(tableName, record);
1359
- const processedRecord = {
1360
- ...record,
1361
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1362
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1363
- metadata: record.metadata ? JSON.stringify(record.metadata) : ""
1364
- };
1318
+ const processedRecord = { ...record };
1365
1319
  await this.validateRecord(processedRecord, tableName);
1366
1320
  await this.putKV({ tableName, key, value: processedRecord });
1367
1321
  } catch (error) {
1368
1322
  throw new MastraError(
1369
1323
  {
1370
- id: "CLOUDFLARE_STORAGE_INSERT_FAILED",
1324
+ id: createStorageErrorId("CLOUDFLARE", "INSERT", "FAILED"),
1371
1325
  domain: ErrorDomain.STORAGE,
1372
1326
  category: ErrorCategory.THIRD_PARTY,
1373
1327
  details: {
@@ -1378,26 +1332,16 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1378
1332
  );
1379
1333
  }
1380
1334
  }
1381
- ensureMetadata(metadata) {
1382
- if (!metadata) return {};
1383
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1384
- }
1385
1335
  async load({ tableName, keys }) {
1386
1336
  try {
1387
1337
  const key = this.getKey(tableName, keys);
1388
1338
  const data = await this.getKV(tableName, key);
1389
1339
  if (!data) return null;
1390
- const processed = {
1391
- ...data,
1392
- createdAt: ensureDate(data.createdAt),
1393
- updatedAt: ensureDate(data.updatedAt),
1394
- metadata: this.ensureMetadata(data.metadata)
1395
- };
1396
- return processed;
1340
+ return data;
1397
1341
  } catch (error) {
1398
1342
  const mastraError = new MastraError(
1399
1343
  {
1400
- id: "CLOUDFLARE_STORAGE_LOAD_FAILED",
1344
+ id: createStorageErrorId("CLOUDFLARE", "LOAD", "FAILED"),
1401
1345
  domain: ErrorDomain.STORAGE,
1402
1346
  category: ErrorCategory.THIRD_PARTY,
1403
1347
  details: {
@@ -1417,19 +1361,13 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1417
1361
  await Promise.all(
1418
1362
  input.records.map(async (record) => {
1419
1363
  const key = this.getKey(input.tableName, record);
1420
- const processedRecord = {
1421
- ...record,
1422
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1423
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1424
- metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
1425
- };
1426
- await this.putKV({ tableName: input.tableName, key, value: processedRecord });
1364
+ await this.putKV({ tableName: input.tableName, key, value: record });
1427
1365
  })
1428
1366
  );
1429
1367
  } catch (error) {
1430
1368
  throw new MastraError(
1431
1369
  {
1432
- id: "CLOUDFLARE_STORAGE_BATCH_INSERT_FAILED",
1370
+ id: createStorageErrorId("CLOUDFLARE", "BATCH_INSERT", "FAILED"),
1433
1371
  domain: ErrorDomain.STORAGE,
1434
1372
  category: ErrorCategory.THIRD_PARTY,
1435
1373
  text: `Error in batch insert for table ${input.tableName}`,
@@ -1501,7 +1439,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1501
1439
  } catch (error) {
1502
1440
  throw new MastraError(
1503
1441
  {
1504
- id: "CLOUDFLARE_STORAGE_CREATE_TABLE_FAILED",
1442
+ id: createStorageErrorId("CLOUDFLARE", "CREATE_TABLE", "FAILED"),
1505
1443
  domain: ErrorDomain.STORAGE,
1506
1444
  category: ErrorCategory.THIRD_PARTY,
1507
1445
  details: {
@@ -1533,7 +1471,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1533
1471
  } catch (error) {
1534
1472
  throw new MastraError(
1535
1473
  {
1536
- id: "CLOUDFLARE_STORAGE_LIST_NAMESPACE_KEYS_FAILED",
1474
+ id: createStorageErrorId("CLOUDFLARE", "LIST_NAMESPACE_KEYS", "FAILED"),
1537
1475
  domain: ErrorDomain.STORAGE,
1538
1476
  category: ErrorCategory.THIRD_PARTY,
1539
1477
  details: {
@@ -1573,17 +1511,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1573
1511
  }
1574
1512
  };
1575
1513
  function transformScoreRow(row) {
1576
- const deserialized = { ...row };
1577
- deserialized.input = safelyParseJSON(row.input);
1578
- deserialized.output = safelyParseJSON(row.output);
1579
- deserialized.scorer = safelyParseJSON(row.scorer);
1580
- deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1581
- deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1582
- deserialized.metadata = safelyParseJSON(row.metadata);
1583
- deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1584
- deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1585
- deserialized.entity = safelyParseJSON(row.entity);
1586
- return deserialized;
1514
+ return transformScoreRow$1(row);
1587
1515
  }
1588
1516
  var ScoresStorageCloudflare = class extends ScoresStorage {
1589
1517
  operations;
@@ -1601,7 +1529,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1601
1529
  } catch (error) {
1602
1530
  const mastraError = new MastraError(
1603
1531
  {
1604
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORE_BY_ID_FAILED",
1532
+ id: createStorageErrorId("CLOUDFLARE", "GET_SCORE_BY_ID", "FAILED"),
1605
1533
  domain: ErrorDomain.STORAGE,
1606
1534
  category: ErrorCategory.THIRD_PARTY,
1607
1535
  text: `Failed to get score by id: ${id}`
@@ -1614,11 +1542,30 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1614
1542
  }
1615
1543
  }
1616
1544
  async saveScore(score) {
1545
+ let parsedScore;
1546
+ try {
1547
+ parsedScore = saveScorePayloadSchema.parse(score);
1548
+ } catch (error) {
1549
+ throw new MastraError(
1550
+ {
1551
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "VALIDATION_FAILED"),
1552
+ domain: ErrorDomain.STORAGE,
1553
+ category: ErrorCategory.USER,
1554
+ details: {
1555
+ scorer: score.scorer?.id ?? "unknown",
1556
+ entityId: score.entityId ?? "unknown",
1557
+ entityType: score.entityType ?? "unknown",
1558
+ traceId: score.traceId ?? "",
1559
+ spanId: score.spanId ?? ""
1560
+ }
1561
+ },
1562
+ error
1563
+ );
1564
+ }
1565
+ const id = crypto.randomUUID();
1617
1566
  try {
1618
- const id = crypto.randomUUID();
1619
- const { input, ...rest } = score;
1620
1567
  const serializedRecord = {};
1621
- for (const [key, value] of Object.entries(rest)) {
1568
+ for (const [key, value] of Object.entries(parsedScore)) {
1622
1569
  if (value !== null && value !== void 0) {
1623
1570
  if (typeof value === "object") {
1624
1571
  serializedRecord[key] = JSON.stringify(value);
@@ -1629,23 +1576,23 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1629
1576
  serializedRecord[key] = null;
1630
1577
  }
1631
1578
  }
1579
+ const now = /* @__PURE__ */ new Date();
1632
1580
  serializedRecord.id = id;
1633
- serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1634
- serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1581
+ serializedRecord.createdAt = now.toISOString();
1582
+ serializedRecord.updatedAt = now.toISOString();
1635
1583
  await this.operations.putKV({
1636
1584
  tableName: TABLE_SCORERS,
1637
1585
  key: id,
1638
1586
  value: serializedRecord
1639
1587
  });
1640
- const scoreFromDb = await this.getScoreById({ id: score.id });
1641
- return { score: scoreFromDb };
1588
+ return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1642
1589
  } catch (error) {
1643
1590
  const mastraError = new MastraError(
1644
1591
  {
1645
- id: "CLOUDFLARE_STORAGE_SCORES_SAVE_SCORE_FAILED",
1592
+ id: createStorageErrorId("CLOUDFLARE", "SAVE_SCORE", "FAILED"),
1646
1593
  domain: ErrorDomain.STORAGE,
1647
1594
  category: ErrorCategory.THIRD_PARTY,
1648
- text: `Failed to save score: ${score.id}`
1595
+ details: { id }
1649
1596
  },
1650
1597
  error
1651
1598
  );
@@ -1654,7 +1601,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1654
1601
  throw mastraError;
1655
1602
  }
1656
1603
  }
1657
- async getScoresByScorerId({
1604
+ async listScoresByScorerId({
1658
1605
  scorerId,
1659
1606
  entityId,
1660
1607
  entityType,
@@ -1684,15 +1631,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1684
1631
  const dateB = new Date(b.createdAt || 0).getTime();
1685
1632
  return dateB - dateA;
1686
1633
  });
1634
+ const { page, perPage: perPageInput } = pagination;
1635
+ const perPage = normalizePerPage(perPageInput, 100);
1636
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1687
1637
  const total = scores.length;
1688
- const start = pagination.page * pagination.perPage;
1689
- const end = start + pagination.perPage;
1638
+ const end = perPageInput === false ? scores.length : start + perPage;
1690
1639
  const pagedScores = scores.slice(start, end);
1691
1640
  return {
1692
1641
  pagination: {
1693
1642
  total,
1694
- page: pagination.page,
1695
- perPage: pagination.perPage,
1643
+ page,
1644
+ perPage: perPageForResponse,
1696
1645
  hasMore: end < total
1697
1646
  },
1698
1647
  scores: pagedScores
@@ -1700,7 +1649,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1700
1649
  } catch (error) {
1701
1650
  const mastraError = new MastraError(
1702
1651
  {
1703
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1652
+ id: createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1704
1653
  domain: ErrorDomain.STORAGE,
1705
1654
  category: ErrorCategory.THIRD_PARTY,
1706
1655
  text: `Failed to get scores by scorer id: ${scorerId}`
@@ -1712,7 +1661,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1712
1661
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1713
1662
  }
1714
1663
  }
1715
- async getScoresByRunId({
1664
+ async listScoresByRunId({
1716
1665
  runId,
1717
1666
  pagination
1718
1667
  }) {
@@ -1730,15 +1679,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1730
1679
  const dateB = new Date(b.createdAt || 0).getTime();
1731
1680
  return dateB - dateA;
1732
1681
  });
1682
+ const { page, perPage: perPageInput } = pagination;
1683
+ const perPage = normalizePerPage(perPageInput, 100);
1684
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1733
1685
  const total = scores.length;
1734
- const start = pagination.page * pagination.perPage;
1735
- const end = start + pagination.perPage;
1686
+ const end = perPageInput === false ? scores.length : start + perPage;
1736
1687
  const pagedScores = scores.slice(start, end);
1737
1688
  return {
1738
1689
  pagination: {
1739
1690
  total,
1740
- page: pagination.page,
1741
- perPage: pagination.perPage,
1691
+ page,
1692
+ perPage: perPageForResponse,
1742
1693
  hasMore: end < total
1743
1694
  },
1744
1695
  scores: pagedScores
@@ -1746,7 +1697,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1746
1697
  } catch (error) {
1747
1698
  const mastraError = new MastraError(
1748
1699
  {
1749
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1700
+ id: createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_RUN_ID", "FAILED"),
1750
1701
  domain: ErrorDomain.STORAGE,
1751
1702
  category: ErrorCategory.THIRD_PARTY,
1752
1703
  text: `Failed to get scores by run id: ${runId}`
@@ -1758,7 +1709,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1758
1709
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1759
1710
  }
1760
1711
  }
1761
- async getScoresByEntityId({
1712
+ async listScoresByEntityId({
1762
1713
  entityId,
1763
1714
  entityType,
1764
1715
  pagination
@@ -1777,15 +1728,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1777
1728
  const dateB = new Date(b.createdAt || 0).getTime();
1778
1729
  return dateB - dateA;
1779
1730
  });
1731
+ const { page, perPage: perPageInput } = pagination;
1732
+ const perPage = normalizePerPage(perPageInput, 100);
1733
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1780
1734
  const total = scores.length;
1781
- const start = pagination.page * pagination.perPage;
1782
- const end = start + pagination.perPage;
1735
+ const end = perPageInput === false ? scores.length : start + perPage;
1783
1736
  const pagedScores = scores.slice(start, end);
1784
1737
  return {
1785
1738
  pagination: {
1786
1739
  total,
1787
- page: pagination.page,
1788
- perPage: pagination.perPage,
1740
+ page,
1741
+ perPage: perPageForResponse,
1789
1742
  hasMore: end < total
1790
1743
  },
1791
1744
  scores: pagedScores
@@ -1793,7 +1746,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1793
1746
  } catch (error) {
1794
1747
  const mastraError = new MastraError(
1795
1748
  {
1796
- id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1749
+ id: createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1797
1750
  domain: ErrorDomain.STORAGE,
1798
1751
  category: ErrorCategory.THIRD_PARTY,
1799
1752
  text: `Failed to get scores by entity id: ${entityId}, type: ${entityType}`
@@ -1805,126 +1758,55 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1805
1758
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1806
1759
  }
1807
1760
  }
1808
- };
1809
- var TracesStorageCloudflare = class extends TracesStorage {
1810
- operations;
1811
- constructor({ operations }) {
1812
- super();
1813
- this.operations = operations;
1814
- }
1815
- async getTraces(args) {
1816
- const paginatedArgs = {
1817
- name: args.name,
1818
- scope: args.scope,
1819
- page: args.page,
1820
- perPage: args.perPage,
1821
- attributes: args.attributes,
1822
- filters: args.filters,
1823
- dateRange: args.fromDate || args.toDate ? {
1824
- start: args.fromDate,
1825
- end: args.toDate
1826
- } : void 0
1827
- };
1828
- try {
1829
- const result = await this.getTracesPaginated(paginatedArgs);
1830
- return result.traces;
1831
- } catch (error) {
1832
- throw new MastraError(
1833
- {
1834
- id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
1835
- domain: ErrorDomain.STORAGE,
1836
- category: ErrorCategory.THIRD_PARTY,
1837
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1838
- details: {
1839
- name: args.name ?? "",
1840
- scope: args.scope ?? ""
1841
- }
1842
- },
1843
- error
1844
- );
1845
- }
1846
- }
1847
- async getTracesPaginated(args) {
1761
+ async listScoresBySpan({
1762
+ traceId,
1763
+ spanId,
1764
+ pagination
1765
+ }) {
1848
1766
  try {
1849
- const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
1850
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
1851
- const keyObjs = await this.operations.listKV(TABLE_TRACES, { prefix: `${prefix}${TABLE_TRACES}` });
1852
- const traces = [];
1853
- for (const { name: key } of keyObjs) {
1854
- try {
1855
- const data = await this.operations.getKV(TABLE_TRACES, key);
1856
- if (!data) continue;
1857
- if (name && data.name !== name) continue;
1858
- if (scope && data.scope !== scope) continue;
1859
- if (attributes) {
1860
- const dataAttributes = data.attributes || {};
1861
- let shouldSkip = false;
1862
- for (const [key2, value] of Object.entries(attributes)) {
1863
- if (dataAttributes[key2] !== value) {
1864
- shouldSkip = true;
1865
- break;
1866
- }
1867
- }
1868
- if (shouldSkip) continue;
1869
- }
1870
- if (dateRange?.start || dateRange?.end) {
1871
- const traceDate = new Date(data.createdAt || 0);
1872
- if (dateRange.start && traceDate < dateRange.start) continue;
1873
- if (dateRange.end && traceDate > dateRange.end) continue;
1874
- }
1875
- if (filters) {
1876
- let shouldSkip = false;
1877
- for (const [key2, value] of Object.entries(filters)) {
1878
- if (data[key2] !== value) {
1879
- shouldSkip = true;
1880
- break;
1881
- }
1882
- }
1883
- if (shouldSkip) continue;
1884
- }
1885
- traces.push(data);
1886
- } catch (err) {
1887
- this.logger.error("Failed to parse trace:", { key, error: err });
1767
+ const keys = await this.operations.listKV(TABLE_SCORERS);
1768
+ const scores = [];
1769
+ for (const { name: key } of keys) {
1770
+ const score = await this.operations.getKV(TABLE_SCORERS, key);
1771
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1772
+ scores.push(transformScoreRow(score));
1888
1773
  }
1889
1774
  }
1890
- traces.sort((a, b) => {
1891
- const aTime = new Date(a.createdAt || 0).getTime();
1892
- const bTime = new Date(b.createdAt || 0).getTime();
1893
- return bTime - aTime;
1775
+ scores.sort((a, b) => {
1776
+ const dateA = new Date(a.createdAt || 0).getTime();
1777
+ const dateB = new Date(b.createdAt || 0).getTime();
1778
+ return dateB - dateA;
1894
1779
  });
1895
- const total = traces.length;
1896
- const start = page * perPage;
1897
- const end = start + perPage;
1898
- const pagedTraces = traces.slice(start, end);
1780
+ const { page, perPage: perPageInput } = pagination;
1781
+ const perPage = normalizePerPage(perPageInput, 100);
1782
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1783
+ const total = scores.length;
1784
+ const end = perPageInput === false ? scores.length : start + perPage;
1785
+ const pagedScores = scores.slice(start, end);
1899
1786
  return {
1900
- traces: pagedTraces,
1901
- total,
1902
- page,
1903
- perPage,
1904
- hasMore: end < total
1787
+ pagination: {
1788
+ total,
1789
+ page,
1790
+ perPage: perPageForResponse,
1791
+ hasMore: end < total
1792
+ },
1793
+ scores: pagedScores
1905
1794
  };
1906
1795
  } catch (error) {
1907
1796
  const mastraError = new MastraError(
1908
1797
  {
1909
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1798
+ id: createStorageErrorId("CLOUDFLARE", "GET_SCORES_BY_SPAN", "FAILED"),
1910
1799
  domain: ErrorDomain.STORAGE,
1911
1800
  category: ErrorCategory.THIRD_PARTY,
1912
- text: "Error getting traces with pagination"
1801
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1913
1802
  },
1914
1803
  error
1915
1804
  );
1916
- this.logger.trackException?.(mastraError);
1917
- this.logger.error(mastraError.toString());
1918
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1805
+ this.logger?.trackException(mastraError);
1806
+ this.logger?.error(mastraError.toString());
1807
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1919
1808
  }
1920
1809
  }
1921
- async batchTraceInsert({ records }) {
1922
- this.logger.debug("Batch inserting traces", { count: records.length });
1923
- await this.operations.batchInsert({
1924
- tableName: TABLE_TRACES,
1925
- records
1926
- });
1927
- }
1928
1810
  };
1929
1811
  var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1930
1812
  operations;
@@ -1943,7 +1825,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1943
1825
  // runId,
1944
1826
  // stepId,
1945
1827
  // result,
1946
- // runtimeContext,
1828
+ // requestContext,
1947
1829
  }) {
1948
1830
  throw new Error("Method not implemented.");
1949
1831
  }
@@ -1964,7 +1846,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1964
1846
  workflow_name: workflowName,
1965
1847
  run_id: runId,
1966
1848
  resourceId,
1967
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1849
+ snapshot: JSON.stringify(snapshot),
1968
1850
  createdAt: /* @__PURE__ */ new Date(),
1969
1851
  updatedAt: /* @__PURE__ */ new Date()
1970
1852
  }
@@ -1972,7 +1854,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1972
1854
  } catch (error) {
1973
1855
  throw new MastraError(
1974
1856
  {
1975
- id: "CLOUDFLARE_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1857
+ id: createStorageErrorId("CLOUDFLARE", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1976
1858
  domain: ErrorDomain.STORAGE,
1977
1859
  category: ErrorCategory.THIRD_PARTY,
1978
1860
  text: `Error persisting workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
@@ -1997,7 +1879,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1997
1879
  } catch (error) {
1998
1880
  const mastraError = new MastraError(
1999
1881
  {
2000
- id: "CLOUDFLARE_STORAGE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1882
+ id: createStorageErrorId("CLOUDFLARE", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2001
1883
  domain: ErrorDomain.STORAGE,
2002
1884
  category: ErrorCategory.THIRD_PARTY,
2003
1885
  text: `Error loading workflow snapshot for workflow ${params.workflowName}, run ${params.runId}`,
@@ -2043,15 +1925,29 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2043
1925
  if (resourceId) key += `:${resourceId}`;
2044
1926
  return key;
2045
1927
  }
2046
- async getWorkflowRuns({
1928
+ async listWorkflowRuns({
2047
1929
  workflowName,
2048
- limit = 20,
2049
- offset = 0,
1930
+ page = 0,
1931
+ perPage = 20,
2050
1932
  resourceId,
2051
1933
  fromDate,
2052
- toDate
1934
+ toDate,
1935
+ status
2053
1936
  } = {}) {
2054
1937
  try {
1938
+ if (page < 0 || !Number.isInteger(page)) {
1939
+ throw new MastraError(
1940
+ {
1941
+ id: createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
1942
+ domain: ErrorDomain.STORAGE,
1943
+ category: ErrorCategory.USER,
1944
+ details: { page }
1945
+ },
1946
+ new Error("page must be a non-negative integer")
1947
+ );
1948
+ }
1949
+ const normalizedPerPage = normalizePerPage(perPage, 20);
1950
+ const offset = page * normalizedPerPage;
2055
1951
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2056
1952
  const keyObjs = await this.operations.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
2057
1953
  const runs = [];
@@ -2067,10 +1963,11 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2067
1963
  if (!data) continue;
2068
1964
  try {
2069
1965
  if (resourceId && !keyResourceId) continue;
1966
+ const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
1967
+ if (status && snapshotData.status !== status) continue;
2070
1968
  const createdAt = ensureDate(data.createdAt);
2071
1969
  if (fromDate && createdAt && createdAt < fromDate) continue;
2072
1970
  if (toDate && createdAt && createdAt > toDate) continue;
2073
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2074
1971
  const resourceIdToUse = keyResourceId || data.resourceId;
2075
1972
  const run = this.parseWorkflowRun({
2076
1973
  ...data,
@@ -2088,7 +1985,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2088
1985
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2089
1986
  return bDate - aDate;
2090
1987
  });
2091
- const pagedRuns = runs.slice(offset, offset + limit);
1988
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2092
1989
  return {
2093
1990
  runs: pagedRuns,
2094
1991
  total: runs.length
@@ -2096,7 +1993,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2096
1993
  } catch (error) {
2097
1994
  const mastraError = new MastraError(
2098
1995
  {
2099
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
1996
+ id: createStorageErrorId("CLOUDFLARE", "LIST_WORKFLOW_RUNS", "FAILED"),
2100
1997
  domain: ErrorDomain.STORAGE,
2101
1998
  category: ErrorCategory.THIRD_PARTY
2102
1999
  },
@@ -2134,7 +2031,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2134
2031
  } catch (error) {
2135
2032
  const mastraError = new MastraError(
2136
2033
  {
2137
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2034
+ id: createStorageErrorId("CLOUDFLARE", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2138
2035
  domain: ErrorDomain.STORAGE,
2139
2036
  category: ErrorCategory.THIRD_PARTY,
2140
2037
  details: {
@@ -2149,6 +2046,28 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2149
2046
  return null;
2150
2047
  }
2151
2048
  }
2049
+ async deleteWorkflowRunById({ runId, workflowName }) {
2050
+ try {
2051
+ if (!runId || !workflowName) {
2052
+ throw new Error("runId and workflowName are required");
2053
+ }
2054
+ const key = this.operations.getKey(TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId });
2055
+ await this.operations.deleteKV(TABLE_WORKFLOW_SNAPSHOT, key);
2056
+ } catch (error) {
2057
+ throw new MastraError(
2058
+ {
2059
+ id: createStorageErrorId("CLOUDFLARE", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2060
+ domain: ErrorDomain.STORAGE,
2061
+ category: ErrorCategory.THIRD_PARTY,
2062
+ details: {
2063
+ workflowName,
2064
+ runId
2065
+ }
2066
+ },
2067
+ error
2068
+ );
2069
+ }
2070
+ }
2152
2071
  };
2153
2072
 
2154
2073
  // src/storage/types.ts
@@ -2170,14 +2089,7 @@ var CloudflareStore = class extends MastraStorage {
2170
2089
  if (!config.bindings) {
2171
2090
  throw new Error("KV bindings are required when using Workers Binding API");
2172
2091
  }
2173
- const requiredTables = [
2174
- TABLE_THREADS,
2175
- TABLE_MESSAGES,
2176
- TABLE_WORKFLOW_SNAPSHOT,
2177
- TABLE_EVALS,
2178
- TABLE_SCORERS,
2179
- TABLE_TRACES
2180
- ];
2092
+ const requiredTables = [TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCORERS];
2181
2093
  for (const table of requiredTables) {
2182
2094
  if (!(table in config.bindings)) {
2183
2095
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2195,8 +2107,15 @@ var CloudflareStore = class extends MastraStorage {
2195
2107
  throw new Error("apiToken is required for REST API");
2196
2108
  }
2197
2109
  }
2110
+ get supports() {
2111
+ const supports = super.supports;
2112
+ supports.listScoresBySpan = true;
2113
+ supports.resourceWorkingMemory = true;
2114
+ supports.selectByIncludeResourceScope = true;
2115
+ return supports;
2116
+ }
2198
2117
  constructor(config) {
2199
- super({ name: "Cloudflare" });
2118
+ super({ id: config.id, name: "Cloudflare", disableInit: config.disableInit });
2200
2119
  try {
2201
2120
  if (isWorkersConfig(config)) {
2202
2121
  this.validateWorkersConfig(config);
@@ -2218,15 +2137,9 @@ var CloudflareStore = class extends MastraStorage {
2218
2137
  namespacePrefix: this.namespacePrefix,
2219
2138
  bindings: this.bindings
2220
2139
  });
2221
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2222
- operations
2223
- });
2224
2140
  const workflows = new WorkflowsStorageCloudflare({
2225
2141
  operations
2226
2142
  });
2227
- const traces = new TracesStorageCloudflare({
2228
- operations
2229
- });
2230
2143
  const memory = new MemoryStorageCloudflare({
2231
2144
  operations
2232
2145
  });
@@ -2235,16 +2148,14 @@ var CloudflareStore = class extends MastraStorage {
2235
2148
  });
2236
2149
  this.stores = {
2237
2150
  operations,
2238
- legacyEvals,
2239
2151
  workflows,
2240
- traces,
2241
2152
  memory,
2242
2153
  scores
2243
2154
  };
2244
2155
  } catch (error) {
2245
2156
  throw new MastraError(
2246
2157
  {
2247
- id: "CLOUDFLARE_STORAGE_INIT_FAILED",
2158
+ id: createStorageErrorId("CLOUDFLARE", "INIT", "FAILED"),
2248
2159
  domain: ErrorDomain.STORAGE,
2249
2160
  category: ErrorCategory.THIRD_PARTY
2250
2161
  },
@@ -2279,9 +2190,6 @@ var CloudflareStore = class extends MastraStorage {
2279
2190
  async getThreadById({ threadId }) {
2280
2191
  return this.stores.memory.getThreadById({ threadId });
2281
2192
  }
2282
- async getThreadsByResourceId({ resourceId }) {
2283
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2284
- }
2285
2193
  async saveThread({ thread }) {
2286
2194
  return this.stores.memory.saveThread({ thread });
2287
2195
  }
@@ -2298,22 +2206,14 @@ var CloudflareStore = class extends MastraStorage {
2298
2206
  async saveMessages(args) {
2299
2207
  return this.stores.memory.saveMessages(args);
2300
2208
  }
2301
- async getMessages({
2302
- threadId,
2303
- resourceId,
2304
- selectBy,
2305
- format
2306
- }) {
2307
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2308
- }
2309
2209
  async updateWorkflowResults({
2310
2210
  workflowName,
2311
2211
  runId,
2312
2212
  stepId,
2313
2213
  result,
2314
- runtimeContext
2214
+ requestContext
2315
2215
  }) {
2316
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2216
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2317
2217
  }
2318
2218
  async updateWorkflowState({
2319
2219
  workflowName,
@@ -2322,11 +2222,8 @@ var CloudflareStore = class extends MastraStorage {
2322
2222
  }) {
2323
2223
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2324
2224
  }
2325
- async getMessagesById({
2326
- messageIds,
2327
- format
2328
- }) {
2329
- return this.stores.memory.getMessagesById({ messageIds, format });
2225
+ async listMessagesById({ messageIds }) {
2226
+ return this.stores.memory.listMessagesById({ messageIds });
2330
2227
  }
2331
2228
  async persistWorkflowSnapshot(params) {
2332
2229
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2337,46 +2234,23 @@ var CloudflareStore = class extends MastraStorage {
2337
2234
  async batchInsert(input) {
2338
2235
  return this.stores.operations.batchInsert(input);
2339
2236
  }
2340
- async getTraces({
2341
- name,
2342
- scope,
2343
- page = 0,
2344
- perPage = 100,
2345
- attributes,
2346
- fromDate,
2347
- toDate
2348
- }) {
2349
- return this.stores.traces.getTraces({
2350
- name,
2351
- scope,
2352
- page,
2353
- perPage,
2354
- attributes,
2355
- fromDate,
2356
- toDate
2357
- });
2358
- }
2359
- async getEvalsByAgentName(agentName, type) {
2360
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2361
- }
2362
- async getEvals(options) {
2363
- return this.stores.legacyEvals.getEvals(options);
2364
- }
2365
- async getWorkflowRuns({
2237
+ async listWorkflowRuns({
2366
2238
  workflowName,
2367
- limit = 20,
2368
- offset = 0,
2239
+ perPage = 20,
2240
+ page = 0,
2369
2241
  resourceId,
2370
2242
  fromDate,
2371
- toDate
2243
+ toDate,
2244
+ status
2372
2245
  } = {}) {
2373
- return this.stores.workflows.getWorkflowRuns({
2246
+ return this.stores.workflows.listWorkflowRuns({
2374
2247
  workflowName,
2375
- limit,
2376
- offset,
2248
+ perPage,
2249
+ page,
2377
2250
  resourceId,
2378
2251
  fromDate,
2379
- toDate
2252
+ toDate,
2253
+ status
2380
2254
  });
2381
2255
  }
2382
2256
  async getWorkflowRunById({
@@ -2385,14 +2259,8 @@ var CloudflareStore = class extends MastraStorage {
2385
2259
  }) {
2386
2260
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2387
2261
  }
2388
- async getTracesPaginated(args) {
2389
- return this.stores.traces.getTracesPaginated(args);
2390
- }
2391
- async getThreadsByResourceIdPaginated(args) {
2392
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2393
- }
2394
- async getMessagesPaginated(args) {
2395
- return this.stores.memory.getMessagesPaginated(args);
2262
+ async deleteWorkflowRunById({ runId, workflowName }) {
2263
+ return this.stores.workflows.deleteWorkflowRunById({ runId, workflowName });
2396
2264
  }
2397
2265
  async updateMessages(args) {
2398
2266
  return this.stores.memory.updateMessages(args);
@@ -2403,27 +2271,34 @@ var CloudflareStore = class extends MastraStorage {
2403
2271
  async saveScore(score) {
2404
2272
  return this.stores.scores.saveScore(score);
2405
2273
  }
2406
- async getScoresByRunId({
2274
+ async listScoresByRunId({
2407
2275
  runId,
2408
2276
  pagination
2409
2277
  }) {
2410
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2278
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2411
2279
  }
2412
- async getScoresByEntityId({
2280
+ async listScoresByEntityId({
2413
2281
  entityId,
2414
2282
  entityType,
2415
2283
  pagination
2416
2284
  }) {
2417
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2285
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2418
2286
  }
2419
- async getScoresByScorerId({
2287
+ async listScoresByScorerId({
2420
2288
  scorerId,
2421
2289
  entityId,
2422
2290
  entityType,
2423
2291
  source,
2424
2292
  pagination
2425
2293
  }) {
2426
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2294
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2295
+ }
2296
+ async listScoresBySpan({
2297
+ traceId,
2298
+ spanId,
2299
+ pagination
2300
+ }) {
2301
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2427
2302
  }
2428
2303
  async getResourceById({ resourceId }) {
2429
2304
  return this.stores.memory.getResourceById({ resourceId });