@mastra/cloudflare-d1 0.0.0-remove-unused-import-20250909212718 → 0.0.0-remove-unused-model-providers-api-20251030210744
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/CHANGELOG.md +169 -3
- package/dist/index.cjs +238 -319
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +239 -320
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +8 -7
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts +8 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +5 -11
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +15 -39
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +9 -9
- package/dist/storage/domains/legacy-evals/index.d.ts +0 -20
- package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
- package/dist/storage/domains/traces/index.d.ts +0 -18
- package/dist/storage/domains/traces/index.d.ts.map +0 -1
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,
|
|
2
|
+
import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, serializeDate, safelyParseJSON } from '@mastra/core/storage';
|
|
3
3
|
import Cloudflare from 'cloudflare';
|
|
4
|
-
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
5
4
|
import { MessageList } from '@mastra/core/agent';
|
|
5
|
+
import { parseSqlIdentifier } from '@mastra/core/utils';
|
|
6
|
+
import { saveScorePayloadSchema } from '@mastra/core/scores';
|
|
6
7
|
|
|
7
8
|
// src/storage/index.ts
|
|
8
9
|
var SqlBuilder = class {
|
|
@@ -241,16 +242,6 @@ function isArrayOfRecords(value) {
|
|
|
241
242
|
}
|
|
242
243
|
function deserializeValue(value, type) {
|
|
243
244
|
if (value === null || value === void 0) return null;
|
|
244
|
-
if (type === "date" && typeof value === "string") {
|
|
245
|
-
return new Date(value);
|
|
246
|
-
}
|
|
247
|
-
if (type === "jsonb" && typeof value === "string") {
|
|
248
|
-
try {
|
|
249
|
-
return JSON.parse(value);
|
|
250
|
-
} catch {
|
|
251
|
-
return value;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
245
|
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
255
246
|
try {
|
|
256
247
|
return JSON.parse(value);
|
|
@@ -261,155 +252,7 @@ function deserializeValue(value, type) {
|
|
|
261
252
|
return value;
|
|
262
253
|
}
|
|
263
254
|
|
|
264
|
-
// src/storage/domains/
|
|
265
|
-
var LegacyEvalsStorageD1 = class extends LegacyEvalsStorage {
|
|
266
|
-
operations;
|
|
267
|
-
constructor({ operations }) {
|
|
268
|
-
super();
|
|
269
|
-
this.operations = operations;
|
|
270
|
-
}
|
|
271
|
-
async getEvals(options) {
|
|
272
|
-
const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
|
|
273
|
-
const fullTableName = this.operations.getTableName(TABLE_EVALS);
|
|
274
|
-
const conditions = [];
|
|
275
|
-
const queryParams = [];
|
|
276
|
-
if (agentName) {
|
|
277
|
-
conditions.push(`agent_name = ?`);
|
|
278
|
-
queryParams.push(agentName);
|
|
279
|
-
}
|
|
280
|
-
if (type === "test") {
|
|
281
|
-
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
282
|
-
} else if (type === "live") {
|
|
283
|
-
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
284
|
-
}
|
|
285
|
-
if (dateRange?.start) {
|
|
286
|
-
conditions.push(`created_at >= ?`);
|
|
287
|
-
queryParams.push(serializeDate(dateRange.start));
|
|
288
|
-
}
|
|
289
|
-
if (dateRange?.end) {
|
|
290
|
-
conditions.push(`created_at <= ?`);
|
|
291
|
-
queryParams.push(serializeDate(dateRange.end));
|
|
292
|
-
}
|
|
293
|
-
const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
|
|
294
|
-
if (conditions.length > 0) {
|
|
295
|
-
countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
296
|
-
}
|
|
297
|
-
const { sql: countSql, params: countParams } = countQueryBuilder.build();
|
|
298
|
-
try {
|
|
299
|
-
const countResult = await this.operations.executeQuery({
|
|
300
|
-
sql: countSql,
|
|
301
|
-
params: countParams,
|
|
302
|
-
first: true
|
|
303
|
-
});
|
|
304
|
-
const total = Number(countResult?.count || 0);
|
|
305
|
-
const currentOffset = page * perPage;
|
|
306
|
-
if (total === 0) {
|
|
307
|
-
return {
|
|
308
|
-
evals: [],
|
|
309
|
-
total: 0,
|
|
310
|
-
page,
|
|
311
|
-
perPage,
|
|
312
|
-
hasMore: false
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
|
|
316
|
-
if (conditions.length > 0) {
|
|
317
|
-
dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
318
|
-
}
|
|
319
|
-
dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
|
|
320
|
-
const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
|
|
321
|
-
const rows = await this.operations.executeQuery({
|
|
322
|
-
sql: dataSql,
|
|
323
|
-
params: dataParams
|
|
324
|
-
});
|
|
325
|
-
const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
|
|
326
|
-
const result = deserializeValue(row.result);
|
|
327
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
328
|
-
if (!result || typeof result !== "object" || !("score" in result)) {
|
|
329
|
-
throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
|
|
330
|
-
}
|
|
331
|
-
return {
|
|
332
|
-
input: row.input,
|
|
333
|
-
output: row.output,
|
|
334
|
-
result,
|
|
335
|
-
agentName: row.agent_name,
|
|
336
|
-
metricName: row.metric_name,
|
|
337
|
-
instructions: row.instructions,
|
|
338
|
-
testInfo,
|
|
339
|
-
globalRunId: row.global_run_id,
|
|
340
|
-
runId: row.run_id,
|
|
341
|
-
createdAt: row.created_at
|
|
342
|
-
};
|
|
343
|
-
});
|
|
344
|
-
const hasMore = currentOffset + evals.length < total;
|
|
345
|
-
return {
|
|
346
|
-
evals,
|
|
347
|
-
total,
|
|
348
|
-
page,
|
|
349
|
-
perPage,
|
|
350
|
-
hasMore
|
|
351
|
-
};
|
|
352
|
-
} catch (error) {
|
|
353
|
-
throw new MastraError(
|
|
354
|
-
{
|
|
355
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
356
|
-
domain: ErrorDomain.STORAGE,
|
|
357
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
358
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
359
|
-
details: { agentName: agentName ?? "", type: type ?? "" }
|
|
360
|
-
},
|
|
361
|
-
error
|
|
362
|
-
);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
/**
|
|
366
|
-
* @deprecated use getEvals instead
|
|
367
|
-
*/
|
|
368
|
-
async getEvalsByAgentName(agentName, type) {
|
|
369
|
-
const fullTableName = this.operations.getTableName(TABLE_EVALS);
|
|
370
|
-
try {
|
|
371
|
-
let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
|
|
372
|
-
if (type === "test") {
|
|
373
|
-
query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
|
|
374
|
-
} else if (type === "live") {
|
|
375
|
-
query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
|
|
376
|
-
}
|
|
377
|
-
query.orderBy("created_at", "DESC");
|
|
378
|
-
const { sql, params } = query.build();
|
|
379
|
-
const results = await this.operations.executeQuery({ sql, params });
|
|
380
|
-
return isArrayOfRecords(results) ? results.map((row) => {
|
|
381
|
-
const result = deserializeValue(row.result);
|
|
382
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
383
|
-
return {
|
|
384
|
-
input: row.input || "",
|
|
385
|
-
output: row.output || "",
|
|
386
|
-
result,
|
|
387
|
-
agentName: row.agent_name || "",
|
|
388
|
-
metricName: row.metric_name || "",
|
|
389
|
-
instructions: row.instructions || "",
|
|
390
|
-
runId: row.run_id || "",
|
|
391
|
-
globalRunId: row.global_run_id || "",
|
|
392
|
-
createdAt: row.created_at || "",
|
|
393
|
-
testInfo
|
|
394
|
-
};
|
|
395
|
-
}) : [];
|
|
396
|
-
} catch (error) {
|
|
397
|
-
const mastraError = new MastraError(
|
|
398
|
-
{
|
|
399
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
400
|
-
domain: ErrorDomain.STORAGE,
|
|
401
|
-
category: ErrorCategory.THIRD_PARTY,
|
|
402
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
403
|
-
details: { agentName }
|
|
404
|
-
},
|
|
405
|
-
error
|
|
406
|
-
);
|
|
407
|
-
this.logger?.error(mastraError.toString());
|
|
408
|
-
this.logger?.trackException(mastraError);
|
|
409
|
-
return [];
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
};
|
|
255
|
+
// src/storage/domains/memory/index.ts
|
|
413
256
|
var MemoryStorageD1 = class extends MemoryStorage {
|
|
414
257
|
operations;
|
|
415
258
|
constructor({ operations }) {
|
|
@@ -922,10 +765,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
922
765
|
throw mastraError;
|
|
923
766
|
}
|
|
924
767
|
}
|
|
925
|
-
async
|
|
926
|
-
messageIds,
|
|
927
|
-
format
|
|
928
|
-
}) {
|
|
768
|
+
async listMessagesById({ messageIds }) {
|
|
929
769
|
if (messageIds.length === 0) return [];
|
|
930
770
|
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
931
771
|
const messages = [];
|
|
@@ -945,7 +785,6 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
945
785
|
});
|
|
946
786
|
this.logger.debug(`Retrieved ${messages.length} messages`);
|
|
947
787
|
const list = new MessageList().add(processedMessages, "memory");
|
|
948
|
-
if (format === `v1`) return list.get.all.v1();
|
|
949
788
|
return list.get.all.v2();
|
|
950
789
|
} catch (error) {
|
|
951
790
|
const mastraError = new MastraError(
|
|
@@ -963,6 +802,169 @@ var MemoryStorageD1 = class extends MemoryStorage {
|
|
|
963
802
|
throw mastraError;
|
|
964
803
|
}
|
|
965
804
|
}
|
|
805
|
+
async listMessages(args) {
|
|
806
|
+
const { threadId, resourceId, include, filter, limit, offset = 0, orderBy } = args;
|
|
807
|
+
if (!threadId.trim()) {
|
|
808
|
+
throw new MastraError(
|
|
809
|
+
{
|
|
810
|
+
id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_THREAD_ID",
|
|
811
|
+
domain: ErrorDomain.STORAGE,
|
|
812
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
813
|
+
details: { threadId }
|
|
814
|
+
},
|
|
815
|
+
new Error("threadId must be a non-empty string")
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
try {
|
|
819
|
+
let perPage = 40;
|
|
820
|
+
if (limit !== void 0) {
|
|
821
|
+
if (limit === false) {
|
|
822
|
+
perPage = Number.MAX_SAFE_INTEGER;
|
|
823
|
+
} else if (limit === 0) {
|
|
824
|
+
perPage = 0;
|
|
825
|
+
} else if (typeof limit === "number" && limit > 0) {
|
|
826
|
+
perPage = limit;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const page = perPage === 0 ? 0 : Math.floor(offset / perPage);
|
|
830
|
+
const sortField = orderBy?.field || "createdAt";
|
|
831
|
+
const sortDirection = orderBy?.direction || "DESC";
|
|
832
|
+
const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
|
|
833
|
+
let query = `
|
|
834
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
835
|
+
FROM ${fullTableName}
|
|
836
|
+
WHERE thread_id = ?
|
|
837
|
+
`;
|
|
838
|
+
const queryParams = [threadId];
|
|
839
|
+
if (resourceId) {
|
|
840
|
+
query += ` AND resourceId = ?`;
|
|
841
|
+
queryParams.push(resourceId);
|
|
842
|
+
}
|
|
843
|
+
const dateRange = filter?.dateRange;
|
|
844
|
+
if (dateRange?.start) {
|
|
845
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
846
|
+
query += ` AND createdAt >= ?`;
|
|
847
|
+
queryParams.push(startDate);
|
|
848
|
+
}
|
|
849
|
+
if (dateRange?.end) {
|
|
850
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
851
|
+
query += ` AND createdAt <= ?`;
|
|
852
|
+
queryParams.push(endDate);
|
|
853
|
+
}
|
|
854
|
+
const orderByField = sortField === "createdAt" ? "createdAt" : `"${sortField}"`;
|
|
855
|
+
const orderByDirection = sortDirection === "ASC" ? "ASC" : "DESC";
|
|
856
|
+
query += ` ORDER BY ${orderByField} ${orderByDirection}`;
|
|
857
|
+
if (perPage !== Number.MAX_SAFE_INTEGER) {
|
|
858
|
+
query += ` LIMIT ? OFFSET ?`;
|
|
859
|
+
queryParams.push(perPage, offset);
|
|
860
|
+
}
|
|
861
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
862
|
+
const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
|
|
863
|
+
const processedMsg = {};
|
|
864
|
+
for (const [key, value] of Object.entries(message)) {
|
|
865
|
+
if (key === `type` && value === `v2`) continue;
|
|
866
|
+
processedMsg[key] = deserializeValue(value);
|
|
867
|
+
}
|
|
868
|
+
return processedMsg;
|
|
869
|
+
});
|
|
870
|
+
const paginatedCount = paginatedMessages.length;
|
|
871
|
+
let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
|
|
872
|
+
const countParams = [threadId];
|
|
873
|
+
if (resourceId) {
|
|
874
|
+
countQuery += ` AND resourceId = ?`;
|
|
875
|
+
countParams.push(resourceId);
|
|
876
|
+
}
|
|
877
|
+
if (dateRange?.start) {
|
|
878
|
+
const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
|
|
879
|
+
countQuery += ` AND createdAt >= ?`;
|
|
880
|
+
countParams.push(startDate);
|
|
881
|
+
}
|
|
882
|
+
if (dateRange?.end) {
|
|
883
|
+
const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
|
|
884
|
+
countQuery += ` AND createdAt <= ?`;
|
|
885
|
+
countParams.push(endDate);
|
|
886
|
+
}
|
|
887
|
+
const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
|
|
888
|
+
const total = Number(countResult[0]?.count ?? 0);
|
|
889
|
+
if (total === 0 && paginatedCount === 0) {
|
|
890
|
+
return {
|
|
891
|
+
messages: [],
|
|
892
|
+
total: 0,
|
|
893
|
+
page,
|
|
894
|
+
perPage,
|
|
895
|
+
hasMore: false
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
const messageIds = new Set(paginatedMessages.map((m) => m.id));
|
|
899
|
+
let includeMessages = [];
|
|
900
|
+
if (include && include.length > 0) {
|
|
901
|
+
const selectBy = { include };
|
|
902
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
903
|
+
if (Array.isArray(includeResult)) {
|
|
904
|
+
includeMessages = includeResult;
|
|
905
|
+
for (const includeMsg of includeMessages) {
|
|
906
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
907
|
+
paginatedMessages.push(includeMsg);
|
|
908
|
+
messageIds.add(includeMsg.id);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const list = new MessageList().add(paginatedMessages, "memory");
|
|
914
|
+
let finalMessages = list.get.all.v2();
|
|
915
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
916
|
+
const aValue = sortField === "createdAt" ? new Date(a.createdAt).getTime() : a[sortField];
|
|
917
|
+
const bValue = sortField === "createdAt" ? new Date(b.createdAt).getTime() : b[sortField];
|
|
918
|
+
if (aValue === bValue) {
|
|
919
|
+
return a.id.localeCompare(b.id);
|
|
920
|
+
}
|
|
921
|
+
return sortDirection === "ASC" ? aValue - bValue : bValue - aValue;
|
|
922
|
+
});
|
|
923
|
+
const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
|
|
924
|
+
const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
|
|
925
|
+
const hasMore = limit === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
|
|
926
|
+
return {
|
|
927
|
+
messages: finalMessages,
|
|
928
|
+
total,
|
|
929
|
+
page,
|
|
930
|
+
perPage,
|
|
931
|
+
hasMore
|
|
932
|
+
};
|
|
933
|
+
} catch (error) {
|
|
934
|
+
const mastraError = new MastraError(
|
|
935
|
+
{
|
|
936
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_ERROR",
|
|
937
|
+
domain: ErrorDomain.STORAGE,
|
|
938
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
939
|
+
text: `Failed to list messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
940
|
+
details: {
|
|
941
|
+
threadId,
|
|
942
|
+
resourceId: resourceId ?? ""
|
|
943
|
+
}
|
|
944
|
+
},
|
|
945
|
+
error
|
|
946
|
+
);
|
|
947
|
+
this.logger?.error?.(mastraError.toString());
|
|
948
|
+
this.logger?.trackException?.(mastraError);
|
|
949
|
+
return {
|
|
950
|
+
messages: [],
|
|
951
|
+
total: 0,
|
|
952
|
+
page: Math.floor(offset / (limit === false ? Number.MAX_SAFE_INTEGER : limit || 40)),
|
|
953
|
+
perPage: limit === false ? Number.MAX_SAFE_INTEGER : limit || 40,
|
|
954
|
+
hasMore: false
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* @todo When migrating from getThreadsByResourceIdPaginated to this method,
|
|
960
|
+
* implement orderBy and sortDirection support for full sorting capabilities
|
|
961
|
+
*/
|
|
962
|
+
async listThreadsByResourceId(args) {
|
|
963
|
+
const { resourceId, limit, offset } = args;
|
|
964
|
+
const page = Math.floor(offset / limit);
|
|
965
|
+
const perPage = limit;
|
|
966
|
+
return this.getThreadsByResourceIdPaginated({ resourceId, page, perPage });
|
|
967
|
+
}
|
|
966
968
|
async getMessagesPaginated({
|
|
967
969
|
threadId,
|
|
968
970
|
resourceId,
|
|
@@ -1575,7 +1577,7 @@ function transformScoreRow(row) {
|
|
|
1575
1577
|
deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
|
|
1576
1578
|
deserialized.metadata = safelyParseJSON(row.metadata);
|
|
1577
1579
|
deserialized.additionalContext = safelyParseJSON(row.additionalContext);
|
|
1578
|
-
deserialized.
|
|
1580
|
+
deserialized.requestContext = safelyParseJSON(row.requestContext);
|
|
1579
1581
|
deserialized.entity = safelyParseJSON(row.entity);
|
|
1580
1582
|
deserialized.createdAt = row.createdAtZ || row.createdAt;
|
|
1581
1583
|
deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
|
|
@@ -1609,12 +1611,25 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1609
1611
|
}
|
|
1610
1612
|
}
|
|
1611
1613
|
async saveScore(score) {
|
|
1614
|
+
let parsedScore;
|
|
1615
|
+
try {
|
|
1616
|
+
parsedScore = saveScorePayloadSchema.parse(score);
|
|
1617
|
+
} catch (error) {
|
|
1618
|
+
throw new MastraError(
|
|
1619
|
+
{
|
|
1620
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
|
|
1621
|
+
domain: ErrorDomain.STORAGE,
|
|
1622
|
+
category: ErrorCategory.USER,
|
|
1623
|
+
details: { scoreId: score.id }
|
|
1624
|
+
},
|
|
1625
|
+
error
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1612
1628
|
try {
|
|
1613
1629
|
const id = crypto.randomUUID();
|
|
1614
1630
|
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1615
|
-
const { input, ...rest } = score;
|
|
1616
1631
|
const serializedRecord = {};
|
|
1617
|
-
for (const [key, value] of Object.entries(
|
|
1632
|
+
for (const [key, value] of Object.entries(parsedScore)) {
|
|
1618
1633
|
if (value !== null && value !== void 0) {
|
|
1619
1634
|
if (typeof value === "object") {
|
|
1620
1635
|
serializedRecord[key] = JSON.stringify(value);
|
|
@@ -1626,7 +1641,6 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1626
1641
|
}
|
|
1627
1642
|
}
|
|
1628
1643
|
serializedRecord.id = id;
|
|
1629
|
-
serializedRecord.input = JSON.stringify(input);
|
|
1630
1644
|
serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1631
1645
|
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1632
1646
|
const columns = Object.keys(serializedRecord);
|
|
@@ -1802,128 +1816,53 @@ var ScoresStorageD1 = class extends ScoresStorage {
|
|
|
1802
1816
|
);
|
|
1803
1817
|
}
|
|
1804
1818
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
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_D1_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) {
|
|
1848
|
-
const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
|
|
1849
|
-
const fromDate = dateRange?.start;
|
|
1850
|
-
const toDate = dateRange?.end;
|
|
1851
|
-
const fullTableName = this.operations.getTableName(TABLE_TRACES);
|
|
1819
|
+
async getScoresBySpan({
|
|
1820
|
+
traceId,
|
|
1821
|
+
spanId,
|
|
1822
|
+
pagination
|
|
1823
|
+
}) {
|
|
1852
1824
|
try {
|
|
1853
|
-
const
|
|
1854
|
-
const countQuery = createSqlBuilder().count().from(fullTableName).where("
|
|
1855
|
-
if (name) {
|
|
1856
|
-
dataQuery.andWhere("name LIKE ?", `%${name}%`);
|
|
1857
|
-
countQuery.andWhere("name LIKE ?", `%${name}%`);
|
|
1858
|
-
}
|
|
1859
|
-
if (scope) {
|
|
1860
|
-
dataQuery.andWhere("scope = ?", scope);
|
|
1861
|
-
countQuery.andWhere("scope = ?", scope);
|
|
1862
|
-
}
|
|
1863
|
-
if (attributes && Object.keys(attributes).length > 0) {
|
|
1864
|
-
for (const [key, value] of Object.entries(attributes)) {
|
|
1865
|
-
dataQuery.jsonLike("attributes", key, value);
|
|
1866
|
-
countQuery.jsonLike("attributes", key, value);
|
|
1867
|
-
}
|
|
1868
|
-
}
|
|
1869
|
-
if (fromDate) {
|
|
1870
|
-
const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
|
|
1871
|
-
dataQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1872
|
-
countQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1873
|
-
}
|
|
1874
|
-
if (toDate) {
|
|
1875
|
-
const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
|
|
1876
|
-
dataQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1877
|
-
countQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1878
|
-
}
|
|
1879
|
-
const allDataResult = await this.operations.executeQuery(
|
|
1880
|
-
createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
|
|
1881
|
-
);
|
|
1882
|
-
console.log("allDataResult", allDataResult);
|
|
1825
|
+
const fullTableName = this.operations.getTableName(TABLE_SCORERS);
|
|
1826
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
|
|
1883
1827
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1884
|
-
const total = Number(countResult?.[0]?.count ?? 0);
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1828
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1829
|
+
if (total === 0) {
|
|
1830
|
+
return {
|
|
1831
|
+
pagination: {
|
|
1832
|
+
total: 0,
|
|
1833
|
+
page: pagination.page,
|
|
1834
|
+
perPage: pagination.perPage,
|
|
1835
|
+
hasMore: false
|
|
1836
|
+
},
|
|
1837
|
+
scores: []
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
const limit = pagination.perPage + 1;
|
|
1841
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
|
|
1842
|
+
const { sql, params } = selectQuery.build();
|
|
1843
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1844
|
+
const rows = Array.isArray(results) ? results : [];
|
|
1845
|
+
const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
|
|
1897
1846
|
return {
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1847
|
+
pagination: {
|
|
1848
|
+
total,
|
|
1849
|
+
page: pagination.page,
|
|
1850
|
+
perPage: pagination.perPage,
|
|
1851
|
+
hasMore: rows.length > pagination.perPage
|
|
1852
|
+
},
|
|
1853
|
+
scores
|
|
1903
1854
|
};
|
|
1904
1855
|
} catch (error) {
|
|
1905
|
-
|
|
1856
|
+
throw new MastraError(
|
|
1906
1857
|
{
|
|
1907
|
-
id: "
|
|
1858
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
|
|
1908
1859
|
domain: ErrorDomain.STORAGE,
|
|
1909
|
-
category: ErrorCategory.THIRD_PARTY
|
|
1910
|
-
text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
|
|
1911
|
-
details: { name: name ?? "", scope: scope ?? "" }
|
|
1860
|
+
category: ErrorCategory.THIRD_PARTY
|
|
1912
1861
|
},
|
|
1913
1862
|
error
|
|
1914
1863
|
);
|
|
1915
|
-
this.logger?.error(mastraError.toString());
|
|
1916
|
-
this.logger?.trackException(mastraError);
|
|
1917
|
-
return { traces: [], total: 0, page, perPage, hasMore: false };
|
|
1918
1864
|
}
|
|
1919
1865
|
}
|
|
1920
|
-
async batchTraceInsert({ records }) {
|
|
1921
|
-
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
1922
|
-
await this.operations.batchInsert({
|
|
1923
|
-
tableName: TABLE_TRACES,
|
|
1924
|
-
records
|
|
1925
|
-
});
|
|
1926
|
-
}
|
|
1927
1866
|
};
|
|
1928
1867
|
var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
1929
1868
|
operations;
|
|
@@ -1936,7 +1875,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
1936
1875
|
// runId,
|
|
1937
1876
|
// stepId,
|
|
1938
1877
|
// result,
|
|
1939
|
-
//
|
|
1878
|
+
// requestContext,
|
|
1940
1879
|
}) {
|
|
1941
1880
|
throw new Error("Method not implemented.");
|
|
1942
1881
|
}
|
|
@@ -1950,6 +1889,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
1950
1889
|
async persistWorkflowSnapshot({
|
|
1951
1890
|
workflowName,
|
|
1952
1891
|
runId,
|
|
1892
|
+
resourceId,
|
|
1953
1893
|
snapshot
|
|
1954
1894
|
}) {
|
|
1955
1895
|
const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
|
|
@@ -1960,11 +1900,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
1960
1900
|
});
|
|
1961
1901
|
const persisting = currentSnapshot ? {
|
|
1962
1902
|
...currentSnapshot,
|
|
1903
|
+
resourceId,
|
|
1963
1904
|
snapshot: JSON.stringify(snapshot),
|
|
1964
1905
|
updatedAt: now
|
|
1965
1906
|
} : {
|
|
1966
1907
|
workflow_name: workflowName,
|
|
1967
1908
|
run_id: runId,
|
|
1909
|
+
resourceId,
|
|
1968
1910
|
snapshot,
|
|
1969
1911
|
createdAt: now,
|
|
1970
1912
|
updatedAt: now
|
|
@@ -2037,7 +1979,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
|
|
|
2037
1979
|
resourceId: row.resourceId
|
|
2038
1980
|
};
|
|
2039
1981
|
}
|
|
2040
|
-
async
|
|
1982
|
+
async listWorkflowRuns({
|
|
2041
1983
|
workflowName,
|
|
2042
1984
|
fromDate,
|
|
2043
1985
|
toDate,
|
|
@@ -2203,12 +2145,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2203
2145
|
const scores = new ScoresStorageD1({
|
|
2204
2146
|
operations
|
|
2205
2147
|
});
|
|
2206
|
-
const legacyEvals = new LegacyEvalsStorageD1({
|
|
2207
|
-
operations
|
|
2208
|
-
});
|
|
2209
|
-
const traces = new TracesStorageD1({
|
|
2210
|
-
operations
|
|
2211
|
-
});
|
|
2212
2148
|
const workflows = new WorkflowsStorageD1({
|
|
2213
2149
|
operations
|
|
2214
2150
|
});
|
|
@@ -2218,8 +2154,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2218
2154
|
this.stores = {
|
|
2219
2155
|
operations,
|
|
2220
2156
|
scores,
|
|
2221
|
-
legacyEvals,
|
|
2222
|
-
traces,
|
|
2223
2157
|
workflows,
|
|
2224
2158
|
memory
|
|
2225
2159
|
};
|
|
@@ -2230,7 +2164,8 @@ var D1Store = class extends MastraStorage {
|
|
|
2230
2164
|
resourceWorkingMemory: true,
|
|
2231
2165
|
hasColumn: true,
|
|
2232
2166
|
createTable: true,
|
|
2233
|
-
deleteMessages: false
|
|
2167
|
+
deleteMessages: false,
|
|
2168
|
+
getScoresBySpan: true
|
|
2234
2169
|
};
|
|
2235
2170
|
}
|
|
2236
2171
|
async createTable({
|
|
@@ -2302,12 +2237,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2302
2237
|
}) {
|
|
2303
2238
|
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
2304
2239
|
}
|
|
2305
|
-
async getMessagesById({
|
|
2306
|
-
messageIds,
|
|
2307
|
-
format
|
|
2308
|
-
}) {
|
|
2309
|
-
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2310
|
-
}
|
|
2311
2240
|
async getMessagesPaginated({
|
|
2312
2241
|
threadId,
|
|
2313
2242
|
selectBy,
|
|
@@ -2320,9 +2249,9 @@ var D1Store = class extends MastraStorage {
|
|
|
2320
2249
|
runId,
|
|
2321
2250
|
stepId,
|
|
2322
2251
|
result,
|
|
2323
|
-
|
|
2252
|
+
requestContext
|
|
2324
2253
|
}) {
|
|
2325
|
-
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result,
|
|
2254
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
2326
2255
|
}
|
|
2327
2256
|
async updateWorkflowState({
|
|
2328
2257
|
workflowName,
|
|
@@ -2334,14 +2263,15 @@ var D1Store = class extends MastraStorage {
|
|
|
2334
2263
|
async persistWorkflowSnapshot({
|
|
2335
2264
|
workflowName,
|
|
2336
2265
|
runId,
|
|
2266
|
+
resourceId,
|
|
2337
2267
|
snapshot
|
|
2338
2268
|
}) {
|
|
2339
|
-
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
|
|
2269
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
|
|
2340
2270
|
}
|
|
2341
2271
|
async loadWorkflowSnapshot(params) {
|
|
2342
2272
|
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2343
2273
|
}
|
|
2344
|
-
async
|
|
2274
|
+
async listWorkflowRuns({
|
|
2345
2275
|
workflowName,
|
|
2346
2276
|
fromDate,
|
|
2347
2277
|
toDate,
|
|
@@ -2349,7 +2279,7 @@ var D1Store = class extends MastraStorage {
|
|
|
2349
2279
|
offset,
|
|
2350
2280
|
resourceId
|
|
2351
2281
|
} = {}) {
|
|
2352
|
-
return this.stores.workflows.
|
|
2282
|
+
return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2353
2283
|
}
|
|
2354
2284
|
async getWorkflowRunById({
|
|
2355
2285
|
runId,
|
|
@@ -2365,24 +2295,6 @@ var D1Store = class extends MastraStorage {
|
|
|
2365
2295
|
async batchInsert({ tableName, records }) {
|
|
2366
2296
|
return this.stores.operations.batchInsert({ tableName, records });
|
|
2367
2297
|
}
|
|
2368
|
-
/**
|
|
2369
|
-
* @deprecated use getTracesPaginated instead
|
|
2370
|
-
*/
|
|
2371
|
-
async getTraces(args) {
|
|
2372
|
-
return this.stores.traces.getTraces(args);
|
|
2373
|
-
}
|
|
2374
|
-
async getTracesPaginated(args) {
|
|
2375
|
-
return this.stores.traces.getTracesPaginated(args);
|
|
2376
|
-
}
|
|
2377
|
-
/**
|
|
2378
|
-
* @deprecated use getEvals instead
|
|
2379
|
-
*/
|
|
2380
|
-
async getEvalsByAgentName(agentName, type) {
|
|
2381
|
-
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2382
|
-
}
|
|
2383
|
-
async getEvals(options) {
|
|
2384
|
-
return this.stores.legacyEvals.getEvals(options);
|
|
2385
|
-
}
|
|
2386
2298
|
async updateMessages(_args) {
|
|
2387
2299
|
return this.stores.memory.updateMessages(_args);
|
|
2388
2300
|
}
|
|
@@ -2431,6 +2343,13 @@ var D1Store = class extends MastraStorage {
|
|
|
2431
2343
|
}) {
|
|
2432
2344
|
return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
2433
2345
|
}
|
|
2346
|
+
async getScoresBySpan({
|
|
2347
|
+
traceId,
|
|
2348
|
+
spanId,
|
|
2349
|
+
pagination
|
|
2350
|
+
}) {
|
|
2351
|
+
return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
|
|
2352
|
+
}
|
|
2434
2353
|
/**
|
|
2435
2354
|
* Close the database connection
|
|
2436
2355
|
* No explicit cleanup needed for D1 in either REST or Workers Binding mode
|