@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.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './storage';
1
+ export * from './storage/index.js';
2
2
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit } from '@mastra/core/storage';
2
+ import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, safelyParseJSON } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { parseSqlIdentifier } from '@mastra/core/utils';
5
5
  import { MessageList } from '@mastra/core/agent';
6
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
6
7
 
7
8
  // src/storage/index.ts
8
9
  var SqlBuilder = class {
@@ -534,7 +535,6 @@ var MemoryStorageD1 = class extends MemoryStorage {
534
535
  keys: { id: threadId }
535
536
  });
536
537
  if (!thread) return null;
537
- console.log("thread", thread);
538
538
  try {
539
539
  return {
540
540
  ...thread,
@@ -803,6 +803,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
803
803
  }
804
804
  }
805
805
  async _getIncludedMessages(threadId, selectBy) {
806
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
806
807
  const include = selectBy?.include;
807
808
  if (!include) return null;
808
809
  const unionQueries = [];
@@ -861,17 +862,19 @@ var MemoryStorageD1 = class extends MemoryStorage {
861
862
  }
862
863
  async getMessages({
863
864
  threadId,
865
+ resourceId,
864
866
  selectBy,
865
867
  format
866
868
  }) {
867
- const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
868
- const limit = resolveMessageLimit({
869
- last: selectBy?.last,
870
- defaultLimit: 40
871
- });
872
- const include = selectBy?.include || [];
873
- const messages = [];
874
869
  try {
870
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
871
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
872
+ const limit = resolveMessageLimit({
873
+ last: selectBy?.last,
874
+ defaultLimit: 40
875
+ });
876
+ const include = selectBy?.include || [];
877
+ const messages = [];
875
878
  if (include.length) {
876
879
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
877
880
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -911,7 +914,48 @@ var MemoryStorageD1 = class extends MemoryStorage {
911
914
  domain: ErrorDomain.STORAGE,
912
915
  category: ErrorCategory.THIRD_PARTY,
913
916
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
914
- details: { threadId }
917
+ details: { threadId, resourceId: resourceId ?? "" }
918
+ },
919
+ error
920
+ );
921
+ this.logger?.error(mastraError.toString());
922
+ this.logger?.trackException(mastraError);
923
+ throw mastraError;
924
+ }
925
+ }
926
+ async getMessagesById({
927
+ messageIds,
928
+ format
929
+ }) {
930
+ if (messageIds.length === 0) return [];
931
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
+ const messages = [];
933
+ try {
934
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
935
+ query.orderBy("createdAt", "DESC");
936
+ const { sql, params } = query.build();
937
+ const result = await this.operations.executeQuery({ sql, params });
938
+ if (Array.isArray(result)) messages.push(...result);
939
+ const processedMessages = messages.map((message) => {
940
+ const processedMsg = {};
941
+ for (const [key, value] of Object.entries(message)) {
942
+ if (key === `type` && value === `v2`) continue;
943
+ processedMsg[key] = deserializeValue(value);
944
+ }
945
+ return processedMsg;
946
+ });
947
+ this.logger.debug(`Retrieved ${messages.length} messages`);
948
+ const list = new MessageList().add(processedMessages, "memory");
949
+ if (format === `v1`) return list.get.all.v1();
950
+ return list.get.all.v2();
951
+ } catch (error) {
952
+ const mastraError = new MastraError(
953
+ {
954
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
955
+ domain: ErrorDomain.STORAGE,
956
+ category: ErrorCategory.THIRD_PARTY,
957
+ text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
958
+ details: { messageIds: JSON.stringify(messageIds) }
915
959
  },
916
960
  error
917
961
  );
@@ -922,6 +966,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
922
966
  }
923
967
  async getMessagesPaginated({
924
968
  threadId,
969
+ resourceId,
925
970
  selectBy,
926
971
  format
927
972
  }) {
@@ -931,6 +976,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
931
976
  const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
977
  const messages = [];
933
978
  try {
979
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
934
980
  if (selectBy?.include?.length) {
935
981
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
936
982
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -1019,7 +1065,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1019
1065
  domain: ErrorDomain.STORAGE,
1020
1066
  category: ErrorCategory.THIRD_PARTY,
1021
1067
  text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1022
- details: { threadId }
1068
+ details: { threadId, resourceId: resourceId ?? "" }
1023
1069
  },
1024
1070
  error
1025
1071
  );
@@ -1437,6 +1483,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1437
1483
  query.andWhere(`${key} = ?`, value);
1438
1484
  }
1439
1485
  }
1486
+ query.orderBy("createdAt", "DESC");
1440
1487
  query.limit(1);
1441
1488
  const { sql, params } = query.build();
1442
1489
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1521,20 +1568,19 @@ var StoreOperationsD1 = class extends StoreOperations {
1521
1568
  }
1522
1569
  };
1523
1570
  function transformScoreRow(row) {
1524
- let input = void 0;
1525
- if (row.input) {
1526
- try {
1527
- input = JSON.parse(row.input);
1528
- } catch {
1529
- input = row.input;
1530
- }
1531
- }
1532
- return {
1533
- ...row,
1534
- input,
1535
- createdAt: row.createdAtZ || row.createdAt,
1536
- updatedAt: row.updatedAtZ || row.updatedAt
1537
- };
1571
+ const deserialized = { ...row };
1572
+ deserialized.input = safelyParseJSON(row.input);
1573
+ deserialized.output = safelyParseJSON(row.output);
1574
+ deserialized.scorer = safelyParseJSON(row.scorer);
1575
+ deserialized.preprocessStepResult = safelyParseJSON(row.preprocessStepResult);
1576
+ deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1577
+ deserialized.metadata = safelyParseJSON(row.metadata);
1578
+ deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1579
+ deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1580
+ deserialized.entity = safelyParseJSON(row.entity);
1581
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1582
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1583
+ return deserialized;
1538
1584
  }
1539
1585
  var ScoresStorageD1 = class extends ScoresStorage {
1540
1586
  operations;
@@ -1564,11 +1610,25 @@ var ScoresStorageD1 = class extends ScoresStorage {
1564
1610
  }
1565
1611
  }
1566
1612
  async saveScore(score) {
1613
+ let parsedScore;
1614
+ try {
1615
+ parsedScore = saveScorePayloadSchema.parse(score);
1616
+ } catch (error) {
1617
+ throw new MastraError(
1618
+ {
1619
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1620
+ domain: ErrorDomain.STORAGE,
1621
+ category: ErrorCategory.USER,
1622
+ details: { scoreId: score.id }
1623
+ },
1624
+ error
1625
+ );
1626
+ }
1567
1627
  try {
1628
+ const id = crypto.randomUUID();
1568
1629
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1569
- const { input, ...rest } = score;
1570
1630
  const serializedRecord = {};
1571
- for (const [key, value] of Object.entries(rest)) {
1631
+ for (const [key, value] of Object.entries(parsedScore)) {
1572
1632
  if (value !== null && value !== void 0) {
1573
1633
  if (typeof value === "object") {
1574
1634
  serializedRecord[key] = JSON.stringify(value);
@@ -1579,7 +1639,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1579
1639
  serializedRecord[key] = null;
1580
1640
  }
1581
1641
  }
1582
- serializedRecord.input = JSON.stringify(input);
1642
+ serializedRecord.id = id;
1583
1643
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1584
1644
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1585
1645
  const columns = Object.keys(serializedRecord);
@@ -1587,7 +1647,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1587
1647
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1588
1648
  const { sql, params } = query.build();
1589
1649
  await this.operations.executeQuery({ sql, params });
1590
- const scoreFromDb = await this.getScoreById({ id: score.id });
1650
+ const scoreFromDb = await this.getScoreById({ id });
1591
1651
  return { score: scoreFromDb };
1592
1652
  } catch (error) {
1593
1653
  throw new MastraError(
@@ -1602,11 +1662,23 @@ var ScoresStorageD1 = class extends ScoresStorage {
1602
1662
  }
1603
1663
  async getScoresByScorerId({
1604
1664
  scorerId,
1665
+ entityId,
1666
+ entityType,
1667
+ source,
1605
1668
  pagination
1606
1669
  }) {
1607
1670
  try {
1608
1671
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1609
1672
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1673
+ if (entityId) {
1674
+ countQuery.andWhere("entityId = ?", entityId);
1675
+ }
1676
+ if (entityType) {
1677
+ countQuery.andWhere("entityType = ?", entityType);
1678
+ }
1679
+ if (source) {
1680
+ countQuery.andWhere("source = ?", source);
1681
+ }
1610
1682
  const countResult = await this.operations.executeQuery(countQuery.build());
1611
1683
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1612
1684
  if (total === 0) {
@@ -1620,7 +1692,17 @@ var ScoresStorageD1 = class extends ScoresStorage {
1620
1692
  scores: []
1621
1693
  };
1622
1694
  }
1623
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1695
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1696
+ if (entityId) {
1697
+ selectQuery.andWhere("entityId = ?", entityId);
1698
+ }
1699
+ if (entityType) {
1700
+ selectQuery.andWhere("entityType = ?", entityType);
1701
+ }
1702
+ if (source) {
1703
+ selectQuery.andWhere("source = ?", source);
1704
+ }
1705
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1624
1706
  const { sql, params } = selectQuery.build();
1625
1707
  const results = await this.operations.executeQuery({ sql, params });
1626
1708
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
@@ -1733,6 +1815,53 @@ var ScoresStorageD1 = class extends ScoresStorage {
1733
1815
  );
1734
1816
  }
1735
1817
  }
1818
+ async getScoresBySpan({
1819
+ traceId,
1820
+ spanId,
1821
+ pagination
1822
+ }) {
1823
+ try {
1824
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1825
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1826
+ const countResult = await this.operations.executeQuery(countQuery.build());
1827
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1828
+ if (total === 0) {
1829
+ return {
1830
+ pagination: {
1831
+ total: 0,
1832
+ page: pagination.page,
1833
+ perPage: pagination.perPage,
1834
+ hasMore: false
1835
+ },
1836
+ scores: []
1837
+ };
1838
+ }
1839
+ const limit = pagination.perPage + 1;
1840
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1841
+ const { sql, params } = selectQuery.build();
1842
+ const results = await this.operations.executeQuery({ sql, params });
1843
+ const rows = Array.isArray(results) ? results : [];
1844
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1845
+ return {
1846
+ pagination: {
1847
+ total,
1848
+ page: pagination.page,
1849
+ perPage: pagination.perPage,
1850
+ hasMore: rows.length > pagination.perPage
1851
+ },
1852
+ scores
1853
+ };
1854
+ } catch (error) {
1855
+ throw new MastraError(
1856
+ {
1857
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1858
+ domain: ErrorDomain.STORAGE,
1859
+ category: ErrorCategory.THIRD_PARTY
1860
+ },
1861
+ error
1862
+ );
1863
+ }
1864
+ }
1736
1865
  };
1737
1866
  function isArrayOfRecords2(value) {
1738
1867
  return value && Array.isArray(value) && value.length > 0;
@@ -1810,7 +1939,7 @@ var TracesStorageD1 = class extends TracesStorage {
1810
1939
  const allDataResult = await this.operations.executeQuery(
1811
1940
  createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1812
1941
  );
1813
- console.log("allDataResult", allDataResult);
1942
+ console.info("allDataResult", allDataResult);
1814
1943
  const countResult = await this.operations.executeQuery(countQuery.build());
1815
1944
  const total = Number(countResult?.[0]?.count ?? 0);
1816
1945
  dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
@@ -1862,9 +1991,26 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1862
1991
  super();
1863
1992
  this.operations = operations;
1864
1993
  }
1994
+ updateWorkflowResults({
1995
+ // workflowName,
1996
+ // runId,
1997
+ // stepId,
1998
+ // result,
1999
+ // runtimeContext,
2000
+ }) {
2001
+ throw new Error("Method not implemented.");
2002
+ }
2003
+ updateWorkflowState({
2004
+ // workflowName,
2005
+ // runId,
2006
+ // opts,
2007
+ }) {
2008
+ throw new Error("Method not implemented.");
2009
+ }
1865
2010
  async persistWorkflowSnapshot({
1866
2011
  workflowName,
1867
2012
  runId,
2013
+ resourceId,
1868
2014
  snapshot
1869
2015
  }) {
1870
2016
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
@@ -1875,11 +2021,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1875
2021
  });
1876
2022
  const persisting = currentSnapshot ? {
1877
2023
  ...currentSnapshot,
2024
+ resourceId,
1878
2025
  snapshot: JSON.stringify(snapshot),
1879
2026
  updatedAt: now
1880
2027
  } : {
1881
2028
  workflow_name: workflowName,
1882
2029
  run_id: runId,
2030
+ resourceId,
1883
2031
  snapshot,
1884
2032
  createdAt: now,
1885
2033
  updatedAt: now
@@ -2145,7 +2293,8 @@ var D1Store = class extends MastraStorage {
2145
2293
  resourceWorkingMemory: true,
2146
2294
  hasColumn: true,
2147
2295
  createTable: true,
2148
- deleteMessages: false
2296
+ deleteMessages: false,
2297
+ getScoresBySpan: true
2149
2298
  };
2150
2299
  }
2151
2300
  async createTable({
@@ -2217,6 +2366,12 @@ var D1Store = class extends MastraStorage {
2217
2366
  }) {
2218
2367
  return this.stores.memory.getMessages({ threadId, selectBy, format });
2219
2368
  }
2369
+ async getMessagesById({
2370
+ messageIds,
2371
+ format
2372
+ }) {
2373
+ return this.stores.memory.getMessagesById({ messageIds, format });
2374
+ }
2220
2375
  async getMessagesPaginated({
2221
2376
  threadId,
2222
2377
  selectBy,
@@ -2224,12 +2379,29 @@ var D1Store = class extends MastraStorage {
2224
2379
  }) {
2225
2380
  return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2226
2381
  }
2382
+ async updateWorkflowResults({
2383
+ workflowName,
2384
+ runId,
2385
+ stepId,
2386
+ result,
2387
+ runtimeContext
2388
+ }) {
2389
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2390
+ }
2391
+ async updateWorkflowState({
2392
+ workflowName,
2393
+ runId,
2394
+ opts
2395
+ }) {
2396
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2397
+ }
2227
2398
  async persistWorkflowSnapshot({
2228
2399
  workflowName,
2229
2400
  runId,
2401
+ resourceId,
2230
2402
  snapshot
2231
2403
  }) {
2232
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2404
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2233
2405
  }
2234
2406
  async loadWorkflowSnapshot(params) {
2235
2407
  return this.stores.workflows.loadWorkflowSnapshot(params);
@@ -2316,10 +2488,20 @@ var D1Store = class extends MastraStorage {
2316
2488
  });
2317
2489
  }
2318
2490
  async getScoresByScorerId({
2319
- scorerId: _scorerId,
2320
- pagination: _pagination
2491
+ scorerId,
2492
+ pagination,
2493
+ entityId,
2494
+ entityType,
2495
+ source
2496
+ }) {
2497
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2498
+ }
2499
+ async getScoresBySpan({
2500
+ traceId,
2501
+ spanId,
2502
+ pagination
2321
2503
  }) {
2322
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2504
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2323
2505
  }
2324
2506
  /**
2325
2507
  * Close the database connection