@mastra/cloudflare-d1 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
@@ -5,6 +5,7 @@ var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
6
  var utils = require('@mastra/core/utils');
7
7
  var agent = require('@mastra/core/agent');
8
+ var scores = require('@mastra/core/scores');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -540,7 +541,6 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
540
541
  keys: { id: threadId }
541
542
  });
542
543
  if (!thread) return null;
543
- console.log("thread", thread);
544
544
  try {
545
545
  return {
546
546
  ...thread,
@@ -809,6 +809,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
809
809
  }
810
810
  }
811
811
  async _getIncludedMessages(threadId, selectBy) {
812
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
812
813
  const include = selectBy?.include;
813
814
  if (!include) return null;
814
815
  const unionQueries = [];
@@ -867,17 +868,19 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
867
868
  }
868
869
  async getMessages({
869
870
  threadId,
871
+ resourceId,
870
872
  selectBy,
871
873
  format
872
874
  }) {
873
- const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
874
- const limit = storage.resolveMessageLimit({
875
- last: selectBy?.last,
876
- defaultLimit: 40
877
- });
878
- const include = selectBy?.include || [];
879
- const messages = [];
880
875
  try {
876
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
877
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
878
+ const limit = storage.resolveMessageLimit({
879
+ last: selectBy?.last,
880
+ defaultLimit: 40
881
+ });
882
+ const include = selectBy?.include || [];
883
+ const messages = [];
881
884
  if (include.length) {
882
885
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
883
886
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -917,7 +920,48 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
917
920
  domain: error.ErrorDomain.STORAGE,
918
921
  category: error.ErrorCategory.THIRD_PARTY,
919
922
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
920
- details: { threadId }
923
+ details: { threadId, resourceId: resourceId ?? "" }
924
+ },
925
+ error$1
926
+ );
927
+ this.logger?.error(mastraError.toString());
928
+ this.logger?.trackException(mastraError);
929
+ throw mastraError;
930
+ }
931
+ }
932
+ async getMessagesById({
933
+ messageIds,
934
+ format
935
+ }) {
936
+ if (messageIds.length === 0) return [];
937
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
+ const messages = [];
939
+ try {
940
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
941
+ query.orderBy("createdAt", "DESC");
942
+ const { sql, params } = query.build();
943
+ const result = await this.operations.executeQuery({ sql, params });
944
+ if (Array.isArray(result)) messages.push(...result);
945
+ const processedMessages = messages.map((message) => {
946
+ const processedMsg = {};
947
+ for (const [key, value] of Object.entries(message)) {
948
+ if (key === `type` && value === `v2`) continue;
949
+ processedMsg[key] = deserializeValue(value);
950
+ }
951
+ return processedMsg;
952
+ });
953
+ this.logger.debug(`Retrieved ${messages.length} messages`);
954
+ const list = new agent.MessageList().add(processedMessages, "memory");
955
+ if (format === `v1`) return list.get.all.v1();
956
+ return list.get.all.v2();
957
+ } catch (error$1) {
958
+ const mastraError = new error.MastraError(
959
+ {
960
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
961
+ domain: error.ErrorDomain.STORAGE,
962
+ category: error.ErrorCategory.THIRD_PARTY,
963
+ text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
964
+ details: { messageIds: JSON.stringify(messageIds) }
921
965
  },
922
966
  error$1
923
967
  );
@@ -928,6 +972,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
928
972
  }
929
973
  async getMessagesPaginated({
930
974
  threadId,
975
+ resourceId,
931
976
  selectBy,
932
977
  format
933
978
  }) {
@@ -937,6 +982,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
937
982
  const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
983
  const messages = [];
939
984
  try {
985
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
940
986
  if (selectBy?.include?.length) {
941
987
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
942
988
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -1025,7 +1071,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
1025
1071
  domain: error.ErrorDomain.STORAGE,
1026
1072
  category: error.ErrorCategory.THIRD_PARTY,
1027
1073
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1028
- details: { threadId }
1074
+ details: { threadId, resourceId: resourceId ?? "" }
1029
1075
  },
1030
1076
  error$1
1031
1077
  );
@@ -1443,6 +1489,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1443
1489
  query.andWhere(`${key} = ?`, value);
1444
1490
  }
1445
1491
  }
1492
+ query.orderBy("createdAt", "DESC");
1446
1493
  query.limit(1);
1447
1494
  const { sql, params } = query.build();
1448
1495
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1527,20 +1574,19 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1527
1574
  }
1528
1575
  };
1529
1576
  function transformScoreRow(row) {
1530
- let input = void 0;
1531
- if (row.input) {
1532
- try {
1533
- input = JSON.parse(row.input);
1534
- } catch {
1535
- input = row.input;
1536
- }
1537
- }
1538
- return {
1539
- ...row,
1540
- input,
1541
- createdAt: row.createdAtZ || row.createdAt,
1542
- updatedAt: row.updatedAtZ || row.updatedAt
1543
- };
1577
+ const deserialized = { ...row };
1578
+ deserialized.input = storage.safelyParseJSON(row.input);
1579
+ deserialized.output = storage.safelyParseJSON(row.output);
1580
+ deserialized.scorer = storage.safelyParseJSON(row.scorer);
1581
+ deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1582
+ deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1583
+ deserialized.metadata = storage.safelyParseJSON(row.metadata);
1584
+ deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1585
+ deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1586
+ deserialized.entity = storage.safelyParseJSON(row.entity);
1587
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1588
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1589
+ return deserialized;
1544
1590
  }
1545
1591
  var ScoresStorageD1 = class extends storage.ScoresStorage {
1546
1592
  operations;
@@ -1570,11 +1616,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1570
1616
  }
1571
1617
  }
1572
1618
  async saveScore(score) {
1619
+ let parsedScore;
1620
+ try {
1621
+ parsedScore = scores.saveScorePayloadSchema.parse(score);
1622
+ } catch (error$1) {
1623
+ throw new error.MastraError(
1624
+ {
1625
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1626
+ domain: error.ErrorDomain.STORAGE,
1627
+ category: error.ErrorCategory.USER,
1628
+ details: { scoreId: score.id }
1629
+ },
1630
+ error$1
1631
+ );
1632
+ }
1573
1633
  try {
1634
+ const id = crypto.randomUUID();
1574
1635
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1575
- const { input, ...rest } = score;
1576
1636
  const serializedRecord = {};
1577
- for (const [key, value] of Object.entries(rest)) {
1637
+ for (const [key, value] of Object.entries(parsedScore)) {
1578
1638
  if (value !== null && value !== void 0) {
1579
1639
  if (typeof value === "object") {
1580
1640
  serializedRecord[key] = JSON.stringify(value);
@@ -1585,7 +1645,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1585
1645
  serializedRecord[key] = null;
1586
1646
  }
1587
1647
  }
1588
- serializedRecord.input = JSON.stringify(input);
1648
+ serializedRecord.id = id;
1589
1649
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1590
1650
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1591
1651
  const columns = Object.keys(serializedRecord);
@@ -1593,7 +1653,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1593
1653
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1594
1654
  const { sql, params } = query.build();
1595
1655
  await this.operations.executeQuery({ sql, params });
1596
- const scoreFromDb = await this.getScoreById({ id: score.id });
1656
+ const scoreFromDb = await this.getScoreById({ id });
1597
1657
  return { score: scoreFromDb };
1598
1658
  } catch (error$1) {
1599
1659
  throw new error.MastraError(
@@ -1608,11 +1668,23 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1608
1668
  }
1609
1669
  async getScoresByScorerId({
1610
1670
  scorerId,
1671
+ entityId,
1672
+ entityType,
1673
+ source,
1611
1674
  pagination
1612
1675
  }) {
1613
1676
  try {
1614
1677
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1615
1678
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1679
+ if (entityId) {
1680
+ countQuery.andWhere("entityId = ?", entityId);
1681
+ }
1682
+ if (entityType) {
1683
+ countQuery.andWhere("entityType = ?", entityType);
1684
+ }
1685
+ if (source) {
1686
+ countQuery.andWhere("source = ?", source);
1687
+ }
1616
1688
  const countResult = await this.operations.executeQuery(countQuery.build());
1617
1689
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1618
1690
  if (total === 0) {
@@ -1626,7 +1698,17 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1626
1698
  scores: []
1627
1699
  };
1628
1700
  }
1629
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1701
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1702
+ if (entityId) {
1703
+ selectQuery.andWhere("entityId = ?", entityId);
1704
+ }
1705
+ if (entityType) {
1706
+ selectQuery.andWhere("entityType = ?", entityType);
1707
+ }
1708
+ if (source) {
1709
+ selectQuery.andWhere("source = ?", source);
1710
+ }
1711
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1630
1712
  const { sql, params } = selectQuery.build();
1631
1713
  const results = await this.operations.executeQuery({ sql, params });
1632
1714
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
@@ -1739,6 +1821,53 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1739
1821
  );
1740
1822
  }
1741
1823
  }
1824
+ async getScoresBySpan({
1825
+ traceId,
1826
+ spanId,
1827
+ pagination
1828
+ }) {
1829
+ try {
1830
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1831
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1832
+ const countResult = await this.operations.executeQuery(countQuery.build());
1833
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1834
+ if (total === 0) {
1835
+ return {
1836
+ pagination: {
1837
+ total: 0,
1838
+ page: pagination.page,
1839
+ perPage: pagination.perPage,
1840
+ hasMore: false
1841
+ },
1842
+ scores: []
1843
+ };
1844
+ }
1845
+ const limit = pagination.perPage + 1;
1846
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1847
+ const { sql, params } = selectQuery.build();
1848
+ const results = await this.operations.executeQuery({ sql, params });
1849
+ const rows = Array.isArray(results) ? results : [];
1850
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1851
+ return {
1852
+ pagination: {
1853
+ total,
1854
+ page: pagination.page,
1855
+ perPage: pagination.perPage,
1856
+ hasMore: rows.length > pagination.perPage
1857
+ },
1858
+ scores
1859
+ };
1860
+ } catch (error$1) {
1861
+ throw new error.MastraError(
1862
+ {
1863
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1864
+ domain: error.ErrorDomain.STORAGE,
1865
+ category: error.ErrorCategory.THIRD_PARTY
1866
+ },
1867
+ error$1
1868
+ );
1869
+ }
1870
+ }
1742
1871
  };
1743
1872
  function isArrayOfRecords2(value) {
1744
1873
  return value && Array.isArray(value) && value.length > 0;
@@ -1816,7 +1945,7 @@ var TracesStorageD1 = class extends storage.TracesStorage {
1816
1945
  const allDataResult = await this.operations.executeQuery(
1817
1946
  createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1818
1947
  );
1819
- console.log("allDataResult", allDataResult);
1948
+ console.info("allDataResult", allDataResult);
1820
1949
  const countResult = await this.operations.executeQuery(countQuery.build());
1821
1950
  const total = Number(countResult?.[0]?.count ?? 0);
1822
1951
  dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
@@ -1868,9 +1997,26 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1868
1997
  super();
1869
1998
  this.operations = operations;
1870
1999
  }
2000
+ updateWorkflowResults({
2001
+ // workflowName,
2002
+ // runId,
2003
+ // stepId,
2004
+ // result,
2005
+ // runtimeContext,
2006
+ }) {
2007
+ throw new Error("Method not implemented.");
2008
+ }
2009
+ updateWorkflowState({
2010
+ // workflowName,
2011
+ // runId,
2012
+ // opts,
2013
+ }) {
2014
+ throw new Error("Method not implemented.");
2015
+ }
1871
2016
  async persistWorkflowSnapshot({
1872
2017
  workflowName,
1873
2018
  runId,
2019
+ resourceId,
1874
2020
  snapshot
1875
2021
  }) {
1876
2022
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
@@ -1881,11 +2027,13 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1881
2027
  });
1882
2028
  const persisting = currentSnapshot ? {
1883
2029
  ...currentSnapshot,
2030
+ resourceId,
1884
2031
  snapshot: JSON.stringify(snapshot),
1885
2032
  updatedAt: now
1886
2033
  } : {
1887
2034
  workflow_name: workflowName,
1888
2035
  run_id: runId,
2036
+ resourceId,
1889
2037
  snapshot,
1890
2038
  createdAt: now,
1891
2039
  updatedAt: now
@@ -2151,7 +2299,8 @@ var D1Store = class extends storage.MastraStorage {
2151
2299
  resourceWorkingMemory: true,
2152
2300
  hasColumn: true,
2153
2301
  createTable: true,
2154
- deleteMessages: false
2302
+ deleteMessages: false,
2303
+ getScoresBySpan: true
2155
2304
  };
2156
2305
  }
2157
2306
  async createTable({
@@ -2223,6 +2372,12 @@ var D1Store = class extends storage.MastraStorage {
2223
2372
  }) {
2224
2373
  return this.stores.memory.getMessages({ threadId, selectBy, format });
2225
2374
  }
2375
+ async getMessagesById({
2376
+ messageIds,
2377
+ format
2378
+ }) {
2379
+ return this.stores.memory.getMessagesById({ messageIds, format });
2380
+ }
2226
2381
  async getMessagesPaginated({
2227
2382
  threadId,
2228
2383
  selectBy,
@@ -2230,12 +2385,29 @@ var D1Store = class extends storage.MastraStorage {
2230
2385
  }) {
2231
2386
  return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2232
2387
  }
2388
+ async updateWorkflowResults({
2389
+ workflowName,
2390
+ runId,
2391
+ stepId,
2392
+ result,
2393
+ runtimeContext
2394
+ }) {
2395
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2396
+ }
2397
+ async updateWorkflowState({
2398
+ workflowName,
2399
+ runId,
2400
+ opts
2401
+ }) {
2402
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2403
+ }
2233
2404
  async persistWorkflowSnapshot({
2234
2405
  workflowName,
2235
2406
  runId,
2407
+ resourceId,
2236
2408
  snapshot
2237
2409
  }) {
2238
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2410
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2239
2411
  }
2240
2412
  async loadWorkflowSnapshot(params) {
2241
2413
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2322,10 +2494,20 @@ var D1Store = class extends storage.MastraStorage {
2322
2494
  });
2323
2495
  }
2324
2496
  async getScoresByScorerId({
2325
- scorerId: _scorerId,
2326
- pagination: _pagination
2497
+ scorerId,
2498
+ pagination,
2499
+ entityId,
2500
+ entityType,
2501
+ source
2502
+ }) {
2503
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2504
+ }
2505
+ async getScoresBySpan({
2506
+ traceId,
2507
+ spanId,
2508
+ pagination
2327
2509
  }) {
2328
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2510
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2329
2511
  }
2330
2512
  /**
2331
2513
  * Close the database connection