@mastra/cloudflare 0.0.0-update-scorers-api-20250801170445 → 0.0.0-usechat-duplicate-20251016110554

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,6 +4,7 @@ var error = require('@mastra/core/error');
4
4
  var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
6
  var agent = require('@mastra/core/agent');
7
+ var scores = require('@mastra/core/scores');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
@@ -469,9 +470,9 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
469
470
  const messageMigrationTasks = [];
470
471
  for (const message of validatedMessages) {
471
472
  const existingMessage = await this.findMessageInAnyThread(message.id);
472
- console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
473
+ console.info(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
473
474
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
474
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
475
+ console.info(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
475
476
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
476
477
  }
477
478
  }
@@ -500,7 +501,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
500
501
  ...cleanMessage,
501
502
  createdAt: storage.serializeDate(cleanMessage.createdAt)
502
503
  };
503
- console.log(`Saving message ${message.id} with content:`, {
504
+ console.info(`Saving message ${message.id} with content:`, {
504
505
  content: serializedMessage.content,
505
506
  contentType: typeof serializedMessage.content,
506
507
  isArray: Array.isArray(serializedMessage.content)
@@ -596,13 +597,14 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
596
597
  );
597
598
  }
598
599
  async getRecentMessages(threadId, limit, messageIds) {
600
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
599
601
  if (limit <= 0) return;
600
602
  try {
601
603
  const threadMessagesKey = this.getThreadMessagesKey(threadId);
602
604
  const latestIds = await this.getLastN(threadMessagesKey, limit);
603
605
  latestIds.forEach((id) => messageIds.add(id));
604
606
  } catch {
605
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
607
+ console.info(`No message order found for thread ${threadId}, skipping latest messages`);
606
608
  }
607
609
  }
608
610
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -633,7 +635,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
633
635
  const data = await this.operations.getKV(storage.TABLE_MESSAGES, key);
634
636
  if (!data) return null;
635
637
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
636
- console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
638
+ console.info(`Retrieved message ${id} from thread ${threadId} with content:`, {
637
639
  content: parsed.content,
638
640
  contentType: typeof parsed.content,
639
641
  isArray: Array.isArray(parsed.content)
@@ -654,15 +656,14 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
654
656
  selectBy,
655
657
  format
656
658
  }) {
657
- console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
658
- if (!threadId) throw new Error("threadId is required");
659
+ console.info(`getMessages called with format: ${format}, threadId: ${threadId}`);
659
660
  const actualFormat = format || "v1";
660
- console.log(`Using format: ${actualFormat}`);
661
- if (!threadId) throw new Error("threadId is required");
661
+ console.info(`Using format: ${actualFormat}`);
662
662
  const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
663
663
  const messageIds = /* @__PURE__ */ new Set();
664
664
  if (limit === 0 && !selectBy?.include?.length) return [];
665
665
  try {
666
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
666
667
  await Promise.all([
667
668
  selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
668
669
  limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
@@ -707,7 +708,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
707
708
  createdAt: storage.ensureDate(message.createdAt)
708
709
  }));
709
710
  if (actualFormat === `v1`) {
710
- console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
711
+ console.info(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
711
712
  return prepared.map((msg) => ({
712
713
  ...msg,
713
714
  createdAt: new Date(msg.createdAt)
@@ -723,7 +724,43 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
723
724
  category: error.ErrorCategory.THIRD_PARTY,
724
725
  text: `Error retrieving messages for thread ${threadId}`,
725
726
  details: {
726
- threadId
727
+ threadId,
728
+ resourceId: resourceId ?? ""
729
+ }
730
+ },
731
+ error$1
732
+ );
733
+ this.logger?.trackException(mastraError);
734
+ this.logger?.error(mastraError.toString());
735
+ return [];
736
+ }
737
+ }
738
+ async getMessagesById({
739
+ messageIds,
740
+ format
741
+ }) {
742
+ if (messageIds.length === 0) return [];
743
+ try {
744
+ const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
745
+ (result) => !!result
746
+ );
747
+ const prepared = messages.map(({ _index, ...message }) => ({
748
+ ...message,
749
+ ...message.type !== `v2` && { type: message.type },
750
+ createdAt: storage.ensureDate(message.createdAt)
751
+ }));
752
+ const list = new agent.MessageList().add(prepared, "memory");
753
+ if (format === `v1`) return list.get.all.v1();
754
+ return list.get.all.v2();
755
+ } catch (error$1) {
756
+ const mastraError = new error.MastraError(
757
+ {
758
+ id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
759
+ domain: error.ErrorDomain.STORAGE,
760
+ category: error.ErrorCategory.THIRD_PARTY,
761
+ text: `Error retrieving messages by ID`,
762
+ details: {
763
+ messageIds: JSON.stringify(messageIds)
727
764
  }
728
765
  },
729
766
  error$1
@@ -734,9 +771,10 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
734
771
  }
735
772
  }
736
773
  async getMessagesPaginated(args) {
774
+ const { threadId, resourceId, selectBy, format = "v1" } = args;
775
+ const { page = 0, perPage = 100 } = selectBy?.pagination || {};
737
776
  try {
738
- const { threadId, selectBy, format = "v1" } = args;
739
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
777
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
740
778
  const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
741
779
  let filteredMessages = messages;
742
780
  if (selectBy?.pagination?.dateRange) {
@@ -759,15 +797,22 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
759
797
  messages: paginatedMessages
760
798
  };
761
799
  } catch (error$1) {
762
- throw new error.MastraError(
800
+ const mastraError = new error.MastraError(
763
801
  {
764
802
  id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
765
803
  domain: error.ErrorDomain.STORAGE,
766
804
  category: error.ErrorCategory.THIRD_PARTY,
767
- text: "Failed to get messages with pagination"
805
+ text: "Failed to get messages with pagination",
806
+ details: {
807
+ threadId,
808
+ resourceId: resourceId ?? ""
809
+ }
768
810
  },
769
811
  error$1
770
812
  );
813
+ this.logger?.trackException?.(mastraError);
814
+ this.logger?.error?.(mastraError.toString());
815
+ return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
771
816
  }
772
817
  }
773
818
  async updateMessages(args) {
@@ -1535,18 +1580,17 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1535
1580
  }
1536
1581
  };
1537
1582
  function transformScoreRow(row) {
1538
- let input = void 0;
1539
- if (row.input) {
1540
- try {
1541
- input = JSON.parse(row.input);
1542
- } catch {
1543
- input = row.input;
1544
- }
1545
- }
1546
- return {
1547
- ...row,
1548
- input
1549
- };
1583
+ const deserialized = { ...row };
1584
+ deserialized.input = storage.safelyParseJSON(row.input);
1585
+ deserialized.output = storage.safelyParseJSON(row.output);
1586
+ deserialized.scorer = storage.safelyParseJSON(row.scorer);
1587
+ deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1588
+ deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1589
+ deserialized.metadata = storage.safelyParseJSON(row.metadata);
1590
+ deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1591
+ deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1592
+ deserialized.entity = storage.safelyParseJSON(row.entity);
1593
+ return deserialized;
1550
1594
  }
1551
1595
  var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1552
1596
  operations;
@@ -1577,10 +1621,24 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1577
1621
  }
1578
1622
  }
1579
1623
  async saveScore(score) {
1624
+ let parsedScore;
1580
1625
  try {
1581
- const { input, ...rest } = score;
1626
+ parsedScore = scores.saveScorePayloadSchema.parse(score);
1627
+ } catch (error$1) {
1628
+ throw new error.MastraError(
1629
+ {
1630
+ id: "CLOUDFLARE_STORAGE_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1631
+ domain: error.ErrorDomain.STORAGE,
1632
+ category: error.ErrorCategory.USER,
1633
+ details: { scoreId: score.id }
1634
+ },
1635
+ error$1
1636
+ );
1637
+ }
1638
+ try {
1639
+ const id = crypto.randomUUID();
1582
1640
  const serializedRecord = {};
1583
- for (const [key, value] of Object.entries(rest)) {
1641
+ for (const [key, value] of Object.entries(parsedScore)) {
1584
1642
  if (value !== null && value !== void 0) {
1585
1643
  if (typeof value === "object") {
1586
1644
  serializedRecord[key] = JSON.stringify(value);
@@ -1591,12 +1649,12 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1591
1649
  serializedRecord[key] = null;
1592
1650
  }
1593
1651
  }
1594
- serializedRecord.input = JSON.stringify(input);
1652
+ serializedRecord.id = id;
1595
1653
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1596
1654
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1597
1655
  await this.operations.putKV({
1598
1656
  tableName: storage.TABLE_SCORERS,
1599
- key: score.id,
1657
+ key: id,
1600
1658
  value: serializedRecord
1601
1659
  });
1602
1660
  const scoreFromDb = await this.getScoreById({ id: score.id });
@@ -1618,6 +1676,9 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1618
1676
  }
1619
1677
  async getScoresByScorerId({
1620
1678
  scorerId,
1679
+ entityId,
1680
+ entityType,
1681
+ source,
1621
1682
  pagination
1622
1683
  }) {
1623
1684
  try {
@@ -1625,6 +1686,15 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1625
1686
  const scores = [];
1626
1687
  for (const { name: key } of keys) {
1627
1688
  const score = await this.operations.getKV(storage.TABLE_SCORERS, key);
1689
+ if (entityId && score.entityId !== entityId) {
1690
+ continue;
1691
+ }
1692
+ if (entityType && score.entityType !== entityType) {
1693
+ continue;
1694
+ }
1695
+ if (source && score.source !== source) {
1696
+ continue;
1697
+ }
1628
1698
  if (score && score.scorerId === scorerId) {
1629
1699
  scores.push(transformScoreRow(score));
1630
1700
  }
@@ -1755,6 +1825,50 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1755
1825
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1756
1826
  }
1757
1827
  }
1828
+ async getScoresBySpan({
1829
+ traceId,
1830
+ spanId,
1831
+ pagination
1832
+ }) {
1833
+ try {
1834
+ const keys = await this.operations.listKV(storage.TABLE_SCORERS);
1835
+ const scores = [];
1836
+ for (const { name: key } of keys) {
1837
+ const score = await this.operations.getKV(storage.TABLE_SCORERS, key);
1838
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1839
+ scores.push(transformScoreRow(score));
1840
+ }
1841
+ }
1842
+ scores.sort((a, b) => {
1843
+ const dateA = new Date(a.createdAt || 0).getTime();
1844
+ const dateB = new Date(b.createdAt || 0).getTime();
1845
+ return dateB - dateA;
1846
+ });
1847
+ const total = scores.length;
1848
+ const start = pagination.page * pagination.perPage;
1849
+ const end = start + pagination.perPage;
1850
+ const pagedScores = scores.slice(start, end);
1851
+ return {
1852
+ pagination: {
1853
+ total,
1854
+ page: pagination.page,
1855
+ perPage: pagination.perPage,
1856
+ hasMore: end < total
1857
+ },
1858
+ scores: pagedScores
1859
+ };
1860
+ } catch (error$1) {
1861
+ throw new error.MastraError(
1862
+ {
1863
+ id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1864
+ domain: error.ErrorDomain.STORAGE,
1865
+ category: error.ErrorCategory.THIRD_PARTY,
1866
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1867
+ },
1868
+ error$1
1869
+ );
1870
+ }
1871
+ }
1758
1872
  };
1759
1873
  var TracesStorageCloudflare = class extends storage.TracesStorage {
1760
1874
  operations;
@@ -1888,15 +2002,32 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1888
2002
  throw new Error("Invalid workflow snapshot parameters");
1889
2003
  }
1890
2004
  }
2005
+ updateWorkflowResults({
2006
+ // workflowName,
2007
+ // runId,
2008
+ // stepId,
2009
+ // result,
2010
+ // runtimeContext,
2011
+ }) {
2012
+ throw new Error("Method not implemented.");
2013
+ }
2014
+ updateWorkflowState({
2015
+ // workflowName,
2016
+ // runId,
2017
+ // opts,
2018
+ }) {
2019
+ throw new Error("Method not implemented.");
2020
+ }
1891
2021
  async persistWorkflowSnapshot(params) {
1892
2022
  try {
1893
- const { workflowName, runId, snapshot } = params;
2023
+ const { workflowName, runId, resourceId, snapshot } = params;
1894
2024
  await this.operations.putKV({
1895
2025
  tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1896
2026
  key: this.operations.getKey(storage.TABLE_WORKFLOW_SNAPSHOT, { workflow_name: workflowName, run_id: runId }),
1897
2027
  value: {
1898
2028
  workflow_name: workflowName,
1899
2029
  run_id: runId,
2030
+ resourceId,
1900
2031
  snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1901
2032
  createdAt: /* @__PURE__ */ new Date(),
1902
2033
  updatedAt: /* @__PURE__ */ new Date()
@@ -2128,6 +2259,11 @@ var CloudflareStore = class extends storage.MastraStorage {
2128
2259
  throw new Error("apiToken is required for REST API");
2129
2260
  }
2130
2261
  }
2262
+ get supports() {
2263
+ const supports = super.supports;
2264
+ supports.getScoresBySpan = true;
2265
+ return supports;
2266
+ }
2131
2267
  constructor(config) {
2132
2268
  super({ name: "Cloudflare" });
2133
2269
  try {
@@ -2239,6 +2375,28 @@ var CloudflareStore = class extends storage.MastraStorage {
2239
2375
  }) {
2240
2376
  return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2241
2377
  }
2378
+ async updateWorkflowResults({
2379
+ workflowName,
2380
+ runId,
2381
+ stepId,
2382
+ result,
2383
+ runtimeContext
2384
+ }) {
2385
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2386
+ }
2387
+ async updateWorkflowState({
2388
+ workflowName,
2389
+ runId,
2390
+ opts
2391
+ }) {
2392
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2393
+ }
2394
+ async getMessagesById({
2395
+ messageIds,
2396
+ format
2397
+ }) {
2398
+ return this.stores.memory.getMessagesById({ messageIds, format });
2399
+ }
2242
2400
  async persistWorkflowSnapshot(params) {
2243
2401
  return this.stores.workflows.persistWorkflowSnapshot(params);
2244
2402
  }
@@ -2329,9 +2487,19 @@ var CloudflareStore = class extends storage.MastraStorage {
2329
2487
  }
2330
2488
  async getScoresByScorerId({
2331
2489
  scorerId,
2490
+ entityId,
2491
+ entityType,
2492
+ source,
2493
+ pagination
2494
+ }) {
2495
+ return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2496
+ }
2497
+ async getScoresBySpan({
2498
+ traceId,
2499
+ spanId,
2332
2500
  pagination
2333
2501
  }) {
2334
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination });
2502
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2335
2503
  }
2336
2504
  async getResourceById({ resourceId }) {
2337
2505
  return this.stores.memory.getResourceById({ resourceId });