@mastra/cloudflare-d1 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-trace-timeline-update-20251121092347
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 +535 -3
- package/README.md +10 -5
- package/dist/index.cjs +275 -569
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +276 -570
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +13 -44
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts +12 -4
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +3 -10
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +30 -86
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +16 -11
- 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.cjs
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
var error = require('@mastra/core/error');
|
|
4
4
|
var storage = require('@mastra/core/storage');
|
|
5
5
|
var Cloudflare = require('cloudflare');
|
|
6
|
-
var utils = require('@mastra/core/utils');
|
|
7
6
|
var agent = require('@mastra/core/agent');
|
|
7
|
+
var utils = require('@mastra/core/utils');
|
|
8
|
+
var evals = require('@mastra/core/evals');
|
|
8
9
|
|
|
9
10
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
11
|
|
|
@@ -247,16 +248,6 @@ function isArrayOfRecords(value) {
|
|
|
247
248
|
}
|
|
248
249
|
function deserializeValue(value, type) {
|
|
249
250
|
if (value === null || value === void 0) return null;
|
|
250
|
-
if (type === "date" && typeof value === "string") {
|
|
251
|
-
return new Date(value);
|
|
252
|
-
}
|
|
253
|
-
if (type === "jsonb" && typeof value === "string") {
|
|
254
|
-
try {
|
|
255
|
-
return JSON.parse(value);
|
|
256
|
-
} catch {
|
|
257
|
-
return value;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
251
|
if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
|
|
261
252
|
try {
|
|
262
253
|
return JSON.parse(value);
|
|
@@ -267,155 +258,7 @@ function deserializeValue(value, type) {
|
|
|
267
258
|
return value;
|
|
268
259
|
}
|
|
269
260
|
|
|
270
|
-
// src/storage/domains/
|
|
271
|
-
var LegacyEvalsStorageD1 = class extends storage.LegacyEvalsStorage {
|
|
272
|
-
operations;
|
|
273
|
-
constructor({ operations }) {
|
|
274
|
-
super();
|
|
275
|
-
this.operations = operations;
|
|
276
|
-
}
|
|
277
|
-
async getEvals(options) {
|
|
278
|
-
const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
|
|
279
|
-
const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
|
|
280
|
-
const conditions = [];
|
|
281
|
-
const queryParams = [];
|
|
282
|
-
if (agentName) {
|
|
283
|
-
conditions.push(`agent_name = ?`);
|
|
284
|
-
queryParams.push(agentName);
|
|
285
|
-
}
|
|
286
|
-
if (type === "test") {
|
|
287
|
-
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
288
|
-
} else if (type === "live") {
|
|
289
|
-
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
290
|
-
}
|
|
291
|
-
if (dateRange?.start) {
|
|
292
|
-
conditions.push(`created_at >= ?`);
|
|
293
|
-
queryParams.push(storage.serializeDate(dateRange.start));
|
|
294
|
-
}
|
|
295
|
-
if (dateRange?.end) {
|
|
296
|
-
conditions.push(`created_at <= ?`);
|
|
297
|
-
queryParams.push(storage.serializeDate(dateRange.end));
|
|
298
|
-
}
|
|
299
|
-
const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
|
|
300
|
-
if (conditions.length > 0) {
|
|
301
|
-
countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
302
|
-
}
|
|
303
|
-
const { sql: countSql, params: countParams } = countQueryBuilder.build();
|
|
304
|
-
try {
|
|
305
|
-
const countResult = await this.operations.executeQuery({
|
|
306
|
-
sql: countSql,
|
|
307
|
-
params: countParams,
|
|
308
|
-
first: true
|
|
309
|
-
});
|
|
310
|
-
const total = Number(countResult?.count || 0);
|
|
311
|
-
const currentOffset = page * perPage;
|
|
312
|
-
if (total === 0) {
|
|
313
|
-
return {
|
|
314
|
-
evals: [],
|
|
315
|
-
total: 0,
|
|
316
|
-
page,
|
|
317
|
-
perPage,
|
|
318
|
-
hasMore: false
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
|
|
322
|
-
if (conditions.length > 0) {
|
|
323
|
-
dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
324
|
-
}
|
|
325
|
-
dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
|
|
326
|
-
const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
|
|
327
|
-
const rows = await this.operations.executeQuery({
|
|
328
|
-
sql: dataSql,
|
|
329
|
-
params: dataParams
|
|
330
|
-
});
|
|
331
|
-
const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
|
|
332
|
-
const result = deserializeValue(row.result);
|
|
333
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
334
|
-
if (!result || typeof result !== "object" || !("score" in result)) {
|
|
335
|
-
throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
|
|
336
|
-
}
|
|
337
|
-
return {
|
|
338
|
-
input: row.input,
|
|
339
|
-
output: row.output,
|
|
340
|
-
result,
|
|
341
|
-
agentName: row.agent_name,
|
|
342
|
-
metricName: row.metric_name,
|
|
343
|
-
instructions: row.instructions,
|
|
344
|
-
testInfo,
|
|
345
|
-
globalRunId: row.global_run_id,
|
|
346
|
-
runId: row.run_id,
|
|
347
|
-
createdAt: row.created_at
|
|
348
|
-
};
|
|
349
|
-
});
|
|
350
|
-
const hasMore = currentOffset + evals.length < total;
|
|
351
|
-
return {
|
|
352
|
-
evals,
|
|
353
|
-
total,
|
|
354
|
-
page,
|
|
355
|
-
perPage,
|
|
356
|
-
hasMore
|
|
357
|
-
};
|
|
358
|
-
} catch (error$1) {
|
|
359
|
-
throw new error.MastraError(
|
|
360
|
-
{
|
|
361
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
362
|
-
domain: error.ErrorDomain.STORAGE,
|
|
363
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
364
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
365
|
-
details: { agentName: agentName ?? "", type: type ?? "" }
|
|
366
|
-
},
|
|
367
|
-
error$1
|
|
368
|
-
);
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
/**
|
|
372
|
-
* @deprecated use getEvals instead
|
|
373
|
-
*/
|
|
374
|
-
async getEvalsByAgentName(agentName, type) {
|
|
375
|
-
const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
|
|
376
|
-
try {
|
|
377
|
-
let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
|
|
378
|
-
if (type === "test") {
|
|
379
|
-
query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
|
|
380
|
-
} else if (type === "live") {
|
|
381
|
-
query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
|
|
382
|
-
}
|
|
383
|
-
query.orderBy("created_at", "DESC");
|
|
384
|
-
const { sql, params } = query.build();
|
|
385
|
-
const results = await this.operations.executeQuery({ sql, params });
|
|
386
|
-
return isArrayOfRecords(results) ? results.map((row) => {
|
|
387
|
-
const result = deserializeValue(row.result);
|
|
388
|
-
const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
|
|
389
|
-
return {
|
|
390
|
-
input: row.input || "",
|
|
391
|
-
output: row.output || "",
|
|
392
|
-
result,
|
|
393
|
-
agentName: row.agent_name || "",
|
|
394
|
-
metricName: row.metric_name || "",
|
|
395
|
-
instructions: row.instructions || "",
|
|
396
|
-
runId: row.run_id || "",
|
|
397
|
-
globalRunId: row.global_run_id || "",
|
|
398
|
-
createdAt: row.created_at || "",
|
|
399
|
-
testInfo
|
|
400
|
-
};
|
|
401
|
-
}) : [];
|
|
402
|
-
} catch (error$1) {
|
|
403
|
-
const mastraError = new error.MastraError(
|
|
404
|
-
{
|
|
405
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
406
|
-
domain: error.ErrorDomain.STORAGE,
|
|
407
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
408
|
-
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
409
|
-
details: { agentName }
|
|
410
|
-
},
|
|
411
|
-
error$1
|
|
412
|
-
);
|
|
413
|
-
this.logger?.error(mastraError.toString());
|
|
414
|
-
this.logger?.trackException(mastraError);
|
|
415
|
-
return [];
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
};
|
|
261
|
+
// src/storage/domains/memory/index.ts
|
|
419
262
|
var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
420
263
|
operations;
|
|
421
264
|
constructor({ operations }) {
|
|
@@ -563,39 +406,22 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
563
406
|
return null;
|
|
564
407
|
}
|
|
565
408
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
try {
|
|
572
|
-
const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
|
|
573
|
-
const { sql, params } = query.build();
|
|
574
|
-
const results = await this.operations.executeQuery({ sql, params });
|
|
575
|
-
return (isArrayOfRecords(results) ? results : []).map((thread) => ({
|
|
576
|
-
...thread,
|
|
577
|
-
createdAt: storage.ensureDate(thread.createdAt),
|
|
578
|
-
updatedAt: storage.ensureDate(thread.updatedAt),
|
|
579
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
580
|
-
}));
|
|
581
|
-
} catch (error$1) {
|
|
582
|
-
const mastraError = new error.MastraError(
|
|
409
|
+
async listThreadsByResourceId(args) {
|
|
410
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
|
|
411
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
412
|
+
if (page < 0) {
|
|
413
|
+
throw new error.MastraError(
|
|
583
414
|
{
|
|
584
|
-
id: "
|
|
415
|
+
id: "STORAGE_CLOUDFLARE_D1_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
|
|
585
416
|
domain: error.ErrorDomain.STORAGE,
|
|
586
|
-
category: error.ErrorCategory.
|
|
587
|
-
|
|
588
|
-
details: { resourceId }
|
|
417
|
+
category: error.ErrorCategory.USER,
|
|
418
|
+
details: { page }
|
|
589
419
|
},
|
|
590
|
-
|
|
420
|
+
new Error("page must be >= 0")
|
|
591
421
|
);
|
|
592
|
-
this.logger?.error(mastraError.toString());
|
|
593
|
-
this.logger?.trackException(mastraError);
|
|
594
|
-
return [];
|
|
595
422
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const { resourceId, page, perPage } = args;
|
|
423
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
424
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
599
425
|
const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
|
|
600
426
|
const mapRowToStorageThreadType = (row) => ({
|
|
601
427
|
...row,
|
|
@@ -607,20 +433,21 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
607
433
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
|
|
608
434
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
609
435
|
const total = Number(countResult?.[0]?.count ?? 0);
|
|
610
|
-
const
|
|
436
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
437
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy(field, direction).limit(limitValue).offset(offset);
|
|
611
438
|
const results = await this.operations.executeQuery(selectQuery.build());
|
|
612
439
|
const threads = results.map(mapRowToStorageThreadType);
|
|
613
440
|
return {
|
|
614
441
|
threads,
|
|
615
442
|
total,
|
|
616
443
|
page,
|
|
617
|
-
perPage,
|
|
618
|
-
hasMore:
|
|
444
|
+
perPage: perPageForResponse,
|
|
445
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
619
446
|
};
|
|
620
447
|
} catch (error$1) {
|
|
621
448
|
const mastraError = new error.MastraError(
|
|
622
449
|
{
|
|
623
|
-
id: "
|
|
450
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_THREADS_BY_RESOURCE_ID_ERROR",
|
|
624
451
|
domain: error.ErrorDomain.STORAGE,
|
|
625
452
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
626
453
|
text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
@@ -634,7 +461,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
634
461
|
threads: [],
|
|
635
462
|
total: 0,
|
|
636
463
|
page,
|
|
637
|
-
perPage,
|
|
464
|
+
perPage: perPageForResponse,
|
|
638
465
|
hasMore: false
|
|
639
466
|
};
|
|
640
467
|
}
|
|
@@ -744,8 +571,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
744
571
|
}
|
|
745
572
|
}
|
|
746
573
|
async saveMessages(args) {
|
|
747
|
-
const { messages
|
|
748
|
-
if (messages.length === 0) return [];
|
|
574
|
+
const { messages } = args;
|
|
575
|
+
if (messages.length === 0) return { messages: [] };
|
|
749
576
|
try {
|
|
750
577
|
const now = /* @__PURE__ */ new Date();
|
|
751
578
|
const threadId = messages[0]?.threadId;
|
|
@@ -793,8 +620,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
793
620
|
]);
|
|
794
621
|
this.logger.debug(`Saved ${messages.length} messages`);
|
|
795
622
|
const list = new agent.MessageList().add(messages, "memory");
|
|
796
|
-
|
|
797
|
-
return list.get.all.v1();
|
|
623
|
+
return { messages: list.get.all.db() };
|
|
798
624
|
} catch (error$1) {
|
|
799
625
|
throw new error.MastraError(
|
|
800
626
|
{
|
|
@@ -807,9 +633,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
807
633
|
);
|
|
808
634
|
}
|
|
809
635
|
}
|
|
810
|
-
async _getIncludedMessages(threadId,
|
|
636
|
+
async _getIncludedMessages(threadId, include) {
|
|
811
637
|
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
812
|
-
const include = selectBy?.include;
|
|
813
638
|
if (!include) return null;
|
|
814
639
|
const unionQueries = [];
|
|
815
640
|
const params = [];
|
|
@@ -865,74 +690,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
865
690
|
});
|
|
866
691
|
return processedMessages;
|
|
867
692
|
}
|
|
868
|
-
async
|
|
869
|
-
|
|
870
|
-
resourceId,
|
|
871
|
-
selectBy,
|
|
872
|
-
format
|
|
873
|
-
}) {
|
|
874
|
-
try {
|
|
875
|
-
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
876
|
-
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
877
|
-
const limit = storage.resolveMessageLimit({
|
|
878
|
-
last: selectBy?.last,
|
|
879
|
-
defaultLimit: 40
|
|
880
|
-
});
|
|
881
|
-
const include = selectBy?.include || [];
|
|
882
|
-
const messages = [];
|
|
883
|
-
if (include.length) {
|
|
884
|
-
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
885
|
-
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
886
|
-
}
|
|
887
|
-
const excludeIds = messages.map((m) => m.id);
|
|
888
|
-
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
889
|
-
if (excludeIds.length > 0) {
|
|
890
|
-
query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
|
|
891
|
-
}
|
|
892
|
-
query.orderBy("createdAt", "DESC").limit(limit);
|
|
893
|
-
const { sql, params } = query.build();
|
|
894
|
-
const result = await this.operations.executeQuery({ sql, params });
|
|
895
|
-
if (Array.isArray(result)) messages.push(...result);
|
|
896
|
-
messages.sort((a, b) => {
|
|
897
|
-
const aRecord = a;
|
|
898
|
-
const bRecord = b;
|
|
899
|
-
const timeA = new Date(aRecord.createdAt).getTime();
|
|
900
|
-
const timeB = new Date(bRecord.createdAt).getTime();
|
|
901
|
-
return timeA - timeB;
|
|
902
|
-
});
|
|
903
|
-
const processedMessages = messages.map((message) => {
|
|
904
|
-
const processedMsg = {};
|
|
905
|
-
for (const [key, value] of Object.entries(message)) {
|
|
906
|
-
if (key === `type` && value === `v2`) continue;
|
|
907
|
-
processedMsg[key] = deserializeValue(value);
|
|
908
|
-
}
|
|
909
|
-
return processedMsg;
|
|
910
|
-
});
|
|
911
|
-
this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
|
|
912
|
-
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
913
|
-
if (format === `v2`) return list.get.all.v2();
|
|
914
|
-
return list.get.all.v1();
|
|
915
|
-
} catch (error$1) {
|
|
916
|
-
const mastraError = new error.MastraError(
|
|
917
|
-
{
|
|
918
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
|
|
919
|
-
domain: error.ErrorDomain.STORAGE,
|
|
920
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
921
|
-
text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
922
|
-
details: { threadId, resourceId: resourceId ?? "" }
|
|
923
|
-
},
|
|
924
|
-
error$1
|
|
925
|
-
);
|
|
926
|
-
this.logger?.error(mastraError.toString());
|
|
927
|
-
this.logger?.trackException(mastraError);
|
|
928
|
-
throw mastraError;
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
async getMessagesById({
|
|
932
|
-
messageIds,
|
|
933
|
-
format
|
|
934
|
-
}) {
|
|
935
|
-
if (messageIds.length === 0) return [];
|
|
693
|
+
async listMessagesById({ messageIds }) {
|
|
694
|
+
if (messageIds.length === 0) return { messages: [] };
|
|
936
695
|
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
937
696
|
const messages = [];
|
|
938
697
|
try {
|
|
@@ -951,12 +710,11 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
951
710
|
});
|
|
952
711
|
this.logger.debug(`Retrieved ${messages.length} messages`);
|
|
953
712
|
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
954
|
-
|
|
955
|
-
return list.get.all.v2();
|
|
713
|
+
return { messages: list.get.all.db() };
|
|
956
714
|
} catch (error$1) {
|
|
957
715
|
const mastraError = new error.MastraError(
|
|
958
716
|
{
|
|
959
|
-
id: "
|
|
717
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_BY_ID_ERROR",
|
|
960
718
|
domain: error.ErrorDomain.STORAGE,
|
|
961
719
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
962
720
|
text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
@@ -969,118 +727,157 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
|
|
|
969
727
|
throw mastraError;
|
|
970
728
|
}
|
|
971
729
|
}
|
|
972
|
-
async
|
|
973
|
-
threadId,
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
730
|
+
async listMessages(args) {
|
|
731
|
+
const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
|
|
732
|
+
if (!threadId.trim()) {
|
|
733
|
+
throw new error.MastraError(
|
|
734
|
+
{
|
|
735
|
+
id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_THREAD_ID",
|
|
736
|
+
domain: error.ErrorDomain.STORAGE,
|
|
737
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
738
|
+
details: { threadId }
|
|
739
|
+
},
|
|
740
|
+
new Error("threadId must be a non-empty string")
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
if (page < 0) {
|
|
744
|
+
throw new error.MastraError(
|
|
745
|
+
{
|
|
746
|
+
id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_PAGE",
|
|
747
|
+
domain: error.ErrorDomain.STORAGE,
|
|
748
|
+
category: error.ErrorCategory.USER,
|
|
749
|
+
details: { page }
|
|
750
|
+
},
|
|
751
|
+
new Error("page must be >= 0")
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
const perPage = storage.normalizePerPage(perPageInput, 40);
|
|
755
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
983
756
|
try {
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
757
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
|
|
758
|
+
let query = `
|
|
759
|
+
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
760
|
+
FROM ${fullTableName}
|
|
761
|
+
WHERE thread_id = ?
|
|
762
|
+
`;
|
|
763
|
+
const queryParams = [threadId];
|
|
764
|
+
if (resourceId) {
|
|
765
|
+
query += ` AND resourceId = ?`;
|
|
766
|
+
queryParams.push(resourceId);
|
|
988
767
|
}
|
|
989
|
-
const
|
|
990
|
-
if (
|
|
991
|
-
|
|
768
|
+
const dateRange = filter?.dateRange;
|
|
769
|
+
if (dateRange?.start) {
|
|
770
|
+
const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
|
|
771
|
+
query += ` AND createdAt >= ?`;
|
|
772
|
+
queryParams.push(startDate);
|
|
992
773
|
}
|
|
993
|
-
if (
|
|
994
|
-
|
|
774
|
+
if (dateRange?.end) {
|
|
775
|
+
const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
|
|
776
|
+
query += ` AND createdAt <= ?`;
|
|
777
|
+
queryParams.push(endDate);
|
|
995
778
|
}
|
|
996
|
-
const
|
|
779
|
+
const { field, direction } = this.parseOrderBy(orderBy, "ASC");
|
|
780
|
+
query += ` ORDER BY "${field}" ${direction}`;
|
|
781
|
+
if (perPage !== Number.MAX_SAFE_INTEGER) {
|
|
782
|
+
query += ` LIMIT ? OFFSET ?`;
|
|
783
|
+
queryParams.push(perPage, offset);
|
|
784
|
+
}
|
|
785
|
+
const results = await this.operations.executeQuery({ sql: query, params: queryParams });
|
|
786
|
+
const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
|
|
787
|
+
const processedMsg = {};
|
|
788
|
+
for (const [key, value] of Object.entries(message)) {
|
|
789
|
+
if (key === `type` && value === `v2`) continue;
|
|
790
|
+
processedMsg[key] = deserializeValue(value);
|
|
791
|
+
}
|
|
792
|
+
return processedMsg;
|
|
793
|
+
});
|
|
794
|
+
const paginatedCount = paginatedMessages.length;
|
|
795
|
+
let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
|
|
796
|
+
const countParams = [threadId];
|
|
797
|
+
if (resourceId) {
|
|
798
|
+
countQuery += ` AND resourceId = ?`;
|
|
799
|
+
countParams.push(resourceId);
|
|
800
|
+
}
|
|
801
|
+
if (dateRange?.start) {
|
|
802
|
+
const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
|
|
803
|
+
countQuery += ` AND createdAt >= ?`;
|
|
804
|
+
countParams.push(startDate);
|
|
805
|
+
}
|
|
806
|
+
if (dateRange?.end) {
|
|
807
|
+
const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
|
|
808
|
+
countQuery += ` AND createdAt <= ?`;
|
|
809
|
+
countParams.push(endDate);
|
|
810
|
+
}
|
|
811
|
+
const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
|
|
997
812
|
const total = Number(countResult[0]?.count ?? 0);
|
|
998
|
-
if (total === 0 &&
|
|
813
|
+
if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
|
|
999
814
|
return {
|
|
1000
815
|
messages: [],
|
|
1001
816
|
total: 0,
|
|
1002
817
|
page,
|
|
1003
|
-
perPage,
|
|
818
|
+
perPage: perPageForResponse,
|
|
1004
819
|
hasMore: false
|
|
1005
820
|
};
|
|
1006
821
|
}
|
|
1007
|
-
const
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
if (selectBy?.last && selectBy.last > 0) {
|
|
1021
|
-
query = `
|
|
1022
|
-
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1023
|
-
FROM ${fullTableName}
|
|
1024
|
-
WHERE thread_id = ?
|
|
1025
|
-
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1026
|
-
${toDate ? "AND createdAt <= ?" : ""}
|
|
1027
|
-
${excludeCondition}
|
|
1028
|
-
ORDER BY createdAt DESC
|
|
1029
|
-
LIMIT ?
|
|
1030
|
-
`;
|
|
1031
|
-
queryParams.push(selectBy.last);
|
|
1032
|
-
} else {
|
|
1033
|
-
query = `
|
|
1034
|
-
SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
|
|
1035
|
-
FROM ${fullTableName}
|
|
1036
|
-
WHERE thread_id = ?
|
|
1037
|
-
${fromDate ? "AND createdAt >= ?" : ""}
|
|
1038
|
-
${toDate ? "AND createdAt <= ?" : ""}
|
|
1039
|
-
${excludeCondition}
|
|
1040
|
-
ORDER BY createdAt DESC
|
|
1041
|
-
LIMIT ? OFFSET ?
|
|
1042
|
-
`;
|
|
1043
|
-
queryParams.push(perPage, page * perPage);
|
|
822
|
+
const messageIds = new Set(paginatedMessages.map((m) => m.id));
|
|
823
|
+
let includeMessages = [];
|
|
824
|
+
if (include && include.length > 0) {
|
|
825
|
+
const includeResult = await this._getIncludedMessages(threadId, include);
|
|
826
|
+
if (Array.isArray(includeResult)) {
|
|
827
|
+
includeMessages = includeResult;
|
|
828
|
+
for (const includeMsg of includeMessages) {
|
|
829
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
830
|
+
paginatedMessages.push(includeMsg);
|
|
831
|
+
messageIds.add(includeMsg.id);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
1044
835
|
}
|
|
1045
|
-
const
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
836
|
+
const list = new agent.MessageList().add(paginatedMessages, "memory");
|
|
837
|
+
let finalMessages = list.get.all.db();
|
|
838
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
839
|
+
const isDateField = field === "createdAt" || field === "updatedAt";
|
|
840
|
+
const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
|
|
841
|
+
const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
|
|
842
|
+
if (aValue === bValue) {
|
|
843
|
+
return a.id.localeCompare(b.id);
|
|
1051
844
|
}
|
|
1052
|
-
|
|
845
|
+
if (typeof aValue === "number" && typeof bValue === "number") {
|
|
846
|
+
return direction === "ASC" ? aValue - bValue : bValue - aValue;
|
|
847
|
+
}
|
|
848
|
+
return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
|
|
1053
849
|
});
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
1058
|
-
messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
|
|
850
|
+
const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
|
|
851
|
+
const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
|
|
852
|
+
const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
|
|
1059
853
|
return {
|
|
1060
|
-
messages,
|
|
854
|
+
messages: finalMessages,
|
|
1061
855
|
total,
|
|
1062
856
|
page,
|
|
1063
|
-
perPage,
|
|
1064
|
-
hasMore
|
|
857
|
+
perPage: perPageForResponse,
|
|
858
|
+
hasMore
|
|
1065
859
|
};
|
|
1066
860
|
} catch (error$1) {
|
|
1067
861
|
const mastraError = new error.MastraError(
|
|
1068
862
|
{
|
|
1069
|
-
id: "
|
|
863
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_ERROR",
|
|
1070
864
|
domain: error.ErrorDomain.STORAGE,
|
|
1071
865
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1072
|
-
text: `Failed to
|
|
1073
|
-
details: {
|
|
866
|
+
text: `Failed to list messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
867
|
+
details: {
|
|
868
|
+
threadId,
|
|
869
|
+
resourceId: resourceId ?? ""
|
|
870
|
+
}
|
|
1074
871
|
},
|
|
1075
872
|
error$1
|
|
1076
873
|
);
|
|
1077
|
-
this.logger?.error(mastraError.toString());
|
|
1078
|
-
this.logger?.trackException(mastraError);
|
|
874
|
+
this.logger?.error?.(mastraError.toString());
|
|
875
|
+
this.logger?.trackException?.(mastraError);
|
|
1079
876
|
return {
|
|
1080
877
|
messages: [],
|
|
1081
878
|
total: 0,
|
|
1082
879
|
page,
|
|
1083
|
-
perPage,
|
|
880
|
+
perPage: perPageForResponse,
|
|
1084
881
|
hasMore: false
|
|
1085
882
|
};
|
|
1086
883
|
}
|
|
@@ -1581,7 +1378,7 @@ function transformScoreRow(row) {
|
|
|
1581
1378
|
deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
|
|
1582
1379
|
deserialized.metadata = storage.safelyParseJSON(row.metadata);
|
|
1583
1380
|
deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
|
|
1584
|
-
deserialized.
|
|
1381
|
+
deserialized.requestContext = storage.safelyParseJSON(row.requestContext);
|
|
1585
1382
|
deserialized.entity = storage.safelyParseJSON(row.entity);
|
|
1586
1383
|
deserialized.createdAt = row.createdAtZ || row.createdAt;
|
|
1587
1384
|
deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
|
|
@@ -1615,12 +1412,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1615
1412
|
}
|
|
1616
1413
|
}
|
|
1617
1414
|
async saveScore(score) {
|
|
1415
|
+
let parsedScore;
|
|
1416
|
+
try {
|
|
1417
|
+
parsedScore = evals.saveScorePayloadSchema.parse(score);
|
|
1418
|
+
} catch (error$1) {
|
|
1419
|
+
throw new error.MastraError(
|
|
1420
|
+
{
|
|
1421
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
|
|
1422
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1423
|
+
category: error.ErrorCategory.USER,
|
|
1424
|
+
details: { scoreId: score.id }
|
|
1425
|
+
},
|
|
1426
|
+
error$1
|
|
1427
|
+
);
|
|
1428
|
+
}
|
|
1618
1429
|
try {
|
|
1619
1430
|
const id = crypto.randomUUID();
|
|
1620
1431
|
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1621
|
-
const { input, ...rest } = score;
|
|
1622
1432
|
const serializedRecord = {};
|
|
1623
|
-
for (const [key, value] of Object.entries(
|
|
1433
|
+
for (const [key, value] of Object.entries(parsedScore)) {
|
|
1624
1434
|
if (value !== null && value !== void 0) {
|
|
1625
1435
|
if (typeof value === "object") {
|
|
1626
1436
|
serializedRecord[key] = JSON.stringify(value);
|
|
@@ -1632,7 +1442,6 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1632
1442
|
}
|
|
1633
1443
|
}
|
|
1634
1444
|
serializedRecord.id = id;
|
|
1635
|
-
serializedRecord.input = JSON.stringify(input);
|
|
1636
1445
|
serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1637
1446
|
serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1638
1447
|
const columns = Object.keys(serializedRecord);
|
|
@@ -1653,7 +1462,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1653
1462
|
);
|
|
1654
1463
|
}
|
|
1655
1464
|
}
|
|
1656
|
-
async
|
|
1465
|
+
async listScoresByScorerId({
|
|
1657
1466
|
scorerId,
|
|
1658
1467
|
entityId,
|
|
1659
1468
|
entityType,
|
|
@@ -1661,6 +1470,9 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1661
1470
|
pagination
|
|
1662
1471
|
}) {
|
|
1663
1472
|
try {
|
|
1473
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1474
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
1475
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1664
1476
|
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1665
1477
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
|
|
1666
1478
|
if (entityId) {
|
|
@@ -1678,13 +1490,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1678
1490
|
return {
|
|
1679
1491
|
pagination: {
|
|
1680
1492
|
total: 0,
|
|
1681
|
-
page
|
|
1682
|
-
perPage:
|
|
1493
|
+
page,
|
|
1494
|
+
perPage: perPageForResponse,
|
|
1683
1495
|
hasMore: false
|
|
1684
1496
|
},
|
|
1685
1497
|
scores: []
|
|
1686
1498
|
};
|
|
1687
1499
|
}
|
|
1500
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1501
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1688
1502
|
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
|
|
1689
1503
|
if (entityId) {
|
|
1690
1504
|
selectQuery.andWhere("entityId = ?", entityId);
|
|
@@ -1695,16 +1509,16 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1695
1509
|
if (source) {
|
|
1696
1510
|
selectQuery.andWhere("source = ?", source);
|
|
1697
1511
|
}
|
|
1698
|
-
selectQuery.limit(
|
|
1512
|
+
selectQuery.limit(limitValue).offset(start);
|
|
1699
1513
|
const { sql, params } = selectQuery.build();
|
|
1700
1514
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1701
1515
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1702
1516
|
return {
|
|
1703
1517
|
pagination: {
|
|
1704
1518
|
total,
|
|
1705
|
-
page
|
|
1706
|
-
perPage:
|
|
1707
|
-
hasMore:
|
|
1519
|
+
page,
|
|
1520
|
+
perPage: perPageForResponse,
|
|
1521
|
+
hasMore: end < total
|
|
1708
1522
|
},
|
|
1709
1523
|
scores
|
|
1710
1524
|
};
|
|
@@ -1719,11 +1533,14 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1719
1533
|
);
|
|
1720
1534
|
}
|
|
1721
1535
|
}
|
|
1722
|
-
async
|
|
1536
|
+
async listScoresByRunId({
|
|
1723
1537
|
runId,
|
|
1724
1538
|
pagination
|
|
1725
1539
|
}) {
|
|
1726
1540
|
try {
|
|
1541
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1542
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
1543
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1727
1544
|
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1728
1545
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
|
|
1729
1546
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
@@ -1732,23 +1549,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1732
1549
|
return {
|
|
1733
1550
|
pagination: {
|
|
1734
1551
|
total: 0,
|
|
1735
|
-
page
|
|
1736
|
-
perPage:
|
|
1552
|
+
page,
|
|
1553
|
+
perPage: perPageForResponse,
|
|
1737
1554
|
hasMore: false
|
|
1738
1555
|
},
|
|
1739
1556
|
scores: []
|
|
1740
1557
|
};
|
|
1741
1558
|
}
|
|
1742
|
-
const
|
|
1559
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1560
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1561
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(limitValue).offset(start);
|
|
1743
1562
|
const { sql, params } = selectQuery.build();
|
|
1744
1563
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1745
1564
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1746
1565
|
return {
|
|
1747
1566
|
pagination: {
|
|
1748
1567
|
total,
|
|
1749
|
-
page
|
|
1750
|
-
perPage:
|
|
1751
|
-
hasMore:
|
|
1568
|
+
page,
|
|
1569
|
+
perPage: perPageForResponse,
|
|
1570
|
+
hasMore: end < total
|
|
1752
1571
|
},
|
|
1753
1572
|
scores
|
|
1754
1573
|
};
|
|
@@ -1763,12 +1582,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1763
1582
|
);
|
|
1764
1583
|
}
|
|
1765
1584
|
}
|
|
1766
|
-
async
|
|
1585
|
+
async listScoresByEntityId({
|
|
1767
1586
|
entityId,
|
|
1768
1587
|
entityType,
|
|
1769
1588
|
pagination
|
|
1770
1589
|
}) {
|
|
1771
1590
|
try {
|
|
1591
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1592
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
1593
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1772
1594
|
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1773
1595
|
const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
|
|
1774
1596
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
@@ -1777,23 +1599,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1777
1599
|
return {
|
|
1778
1600
|
pagination: {
|
|
1779
1601
|
total: 0,
|
|
1780
|
-
page
|
|
1781
|
-
perPage:
|
|
1602
|
+
page,
|
|
1603
|
+
perPage: perPageForResponse,
|
|
1782
1604
|
hasMore: false
|
|
1783
1605
|
},
|
|
1784
1606
|
scores: []
|
|
1785
1607
|
};
|
|
1786
1608
|
}
|
|
1787
|
-
const
|
|
1609
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1610
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1611
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(limitValue).offset(start);
|
|
1788
1612
|
const { sql, params } = selectQuery.build();
|
|
1789
1613
|
const results = await this.operations.executeQuery({ sql, params });
|
|
1790
1614
|
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1791
1615
|
return {
|
|
1792
1616
|
pagination: {
|
|
1793
1617
|
total,
|
|
1794
|
-
page
|
|
1795
|
-
perPage:
|
|
1796
|
-
hasMore:
|
|
1618
|
+
page,
|
|
1619
|
+
perPage: perPageForResponse,
|
|
1620
|
+
hasMore: end < total
|
|
1797
1621
|
},
|
|
1798
1622
|
scores
|
|
1799
1623
|
};
|
|
@@ -1808,128 +1632,56 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
|
|
|
1808
1632
|
);
|
|
1809
1633
|
}
|
|
1810
1634
|
}
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
operations;
|
|
1817
|
-
constructor({ operations }) {
|
|
1818
|
-
super();
|
|
1819
|
-
this.operations = operations;
|
|
1820
|
-
}
|
|
1821
|
-
async getTraces(args) {
|
|
1822
|
-
const paginatedArgs = {
|
|
1823
|
-
name: args.name,
|
|
1824
|
-
scope: args.scope,
|
|
1825
|
-
page: args.page,
|
|
1826
|
-
perPage: args.perPage,
|
|
1827
|
-
attributes: args.attributes,
|
|
1828
|
-
filters: args.filters,
|
|
1829
|
-
dateRange: args.fromDate || args.toDate ? {
|
|
1830
|
-
start: args.fromDate,
|
|
1831
|
-
end: args.toDate
|
|
1832
|
-
} : void 0
|
|
1833
|
-
};
|
|
1834
|
-
try {
|
|
1835
|
-
const result = await this.getTracesPaginated(paginatedArgs);
|
|
1836
|
-
return result.traces;
|
|
1837
|
-
} catch (error$1) {
|
|
1838
|
-
throw new error.MastraError(
|
|
1839
|
-
{
|
|
1840
|
-
id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
|
|
1841
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1842
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1843
|
-
text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1844
|
-
details: {
|
|
1845
|
-
name: args.name ?? "",
|
|
1846
|
-
scope: args.scope ?? ""
|
|
1847
|
-
}
|
|
1848
|
-
},
|
|
1849
|
-
error$1
|
|
1850
|
-
);
|
|
1851
|
-
}
|
|
1852
|
-
}
|
|
1853
|
-
async getTracesPaginated(args) {
|
|
1854
|
-
const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
|
|
1855
|
-
const fromDate = dateRange?.start;
|
|
1856
|
-
const toDate = dateRange?.end;
|
|
1857
|
-
const fullTableName = this.operations.getTableName(storage.TABLE_TRACES);
|
|
1635
|
+
async listScoresBySpan({
|
|
1636
|
+
traceId,
|
|
1637
|
+
spanId,
|
|
1638
|
+
pagination
|
|
1639
|
+
}) {
|
|
1858
1640
|
try {
|
|
1859
|
-
const
|
|
1860
|
-
const
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
}
|
|
1865
|
-
if (scope) {
|
|
1866
|
-
dataQuery.andWhere("scope = ?", scope);
|
|
1867
|
-
countQuery.andWhere("scope = ?", scope);
|
|
1868
|
-
}
|
|
1869
|
-
if (attributes && Object.keys(attributes).length > 0) {
|
|
1870
|
-
for (const [key, value] of Object.entries(attributes)) {
|
|
1871
|
-
dataQuery.jsonLike("attributes", key, value);
|
|
1872
|
-
countQuery.jsonLike("attributes", key, value);
|
|
1873
|
-
}
|
|
1874
|
-
}
|
|
1875
|
-
if (fromDate) {
|
|
1876
|
-
const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
|
|
1877
|
-
dataQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1878
|
-
countQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1879
|
-
}
|
|
1880
|
-
if (toDate) {
|
|
1881
|
-
const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
|
|
1882
|
-
dataQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1883
|
-
countQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1884
|
-
}
|
|
1885
|
-
const allDataResult = await this.operations.executeQuery(
|
|
1886
|
-
createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
|
|
1887
|
-
);
|
|
1888
|
-
console.log("allDataResult", allDataResult);
|
|
1641
|
+
const { page, perPage: perPageInput } = pagination;
|
|
1642
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
1643
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1644
|
+
const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
|
|
1645
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
|
|
1889
1646
|
const countResult = await this.operations.executeQuery(countQuery.build());
|
|
1890
|
-
const total = Number(countResult?.[0]?.count ?? 0);
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1647
|
+
const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
|
|
1648
|
+
if (total === 0) {
|
|
1649
|
+
return {
|
|
1650
|
+
pagination: {
|
|
1651
|
+
total: 0,
|
|
1652
|
+
page,
|
|
1653
|
+
perPage: perPageForResponse,
|
|
1654
|
+
hasMore: false
|
|
1655
|
+
},
|
|
1656
|
+
scores: []
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
1660
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1661
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limitValue).offset(start);
|
|
1662
|
+
const { sql, params } = selectQuery.build();
|
|
1663
|
+
const results = await this.operations.executeQuery({ sql, params });
|
|
1664
|
+
const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
|
|
1903
1665
|
return {
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1666
|
+
pagination: {
|
|
1667
|
+
total,
|
|
1668
|
+
page,
|
|
1669
|
+
perPage: perPageForResponse,
|
|
1670
|
+
hasMore: end < total
|
|
1671
|
+
},
|
|
1672
|
+
scores
|
|
1909
1673
|
};
|
|
1910
1674
|
} catch (error$1) {
|
|
1911
|
-
|
|
1675
|
+
throw new error.MastraError(
|
|
1912
1676
|
{
|
|
1913
|
-
id: "
|
|
1677
|
+
id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
|
|
1914
1678
|
domain: error.ErrorDomain.STORAGE,
|
|
1915
|
-
category: error.ErrorCategory.THIRD_PARTY
|
|
1916
|
-
text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1917
|
-
details: { name: name ?? "", scope: scope ?? "" }
|
|
1679
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1918
1680
|
},
|
|
1919
1681
|
error$1
|
|
1920
1682
|
);
|
|
1921
|
-
this.logger?.error(mastraError.toString());
|
|
1922
|
-
this.logger?.trackException(mastraError);
|
|
1923
|
-
return { traces: [], total: 0, page, perPage, hasMore: false };
|
|
1924
1683
|
}
|
|
1925
1684
|
}
|
|
1926
|
-
async batchTraceInsert({ records }) {
|
|
1927
|
-
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
1928
|
-
await this.operations.batchInsert({
|
|
1929
|
-
tableName: storage.TABLE_TRACES,
|
|
1930
|
-
records
|
|
1931
|
-
});
|
|
1932
|
-
}
|
|
1933
1685
|
};
|
|
1934
1686
|
var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
1935
1687
|
operations;
|
|
@@ -1942,7 +1694,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
|
1942
1694
|
// runId,
|
|
1943
1695
|
// stepId,
|
|
1944
1696
|
// result,
|
|
1945
|
-
//
|
|
1697
|
+
// requestContext,
|
|
1946
1698
|
}) {
|
|
1947
1699
|
throw new Error("Method not implemented.");
|
|
1948
1700
|
}
|
|
@@ -2046,19 +1798,24 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
|
2046
1798
|
resourceId: row.resourceId
|
|
2047
1799
|
};
|
|
2048
1800
|
}
|
|
2049
|
-
async
|
|
1801
|
+
async listWorkflowRuns({
|
|
2050
1802
|
workflowName,
|
|
2051
1803
|
fromDate,
|
|
2052
1804
|
toDate,
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
resourceId
|
|
1805
|
+
page,
|
|
1806
|
+
perPage,
|
|
1807
|
+
resourceId,
|
|
1808
|
+
status
|
|
2056
1809
|
} = {}) {
|
|
2057
1810
|
const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
|
|
2058
1811
|
try {
|
|
2059
1812
|
const builder = createSqlBuilder().select().from(fullTableName);
|
|
2060
1813
|
const countBuilder = createSqlBuilder().count().from(fullTableName);
|
|
2061
1814
|
if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
|
|
1815
|
+
if (status) {
|
|
1816
|
+
builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
|
|
1817
|
+
countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
|
|
1818
|
+
}
|
|
2062
1819
|
if (resourceId) {
|
|
2063
1820
|
const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
|
|
2064
1821
|
if (hasResourceId) {
|
|
@@ -2077,11 +1834,14 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
|
2077
1834
|
countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
2078
1835
|
}
|
|
2079
1836
|
builder.orderBy("createdAt", "DESC");
|
|
2080
|
-
if (typeof
|
|
2081
|
-
|
|
1837
|
+
if (typeof perPage === "number" && typeof page === "number") {
|
|
1838
|
+
const offset = page * perPage;
|
|
1839
|
+
builder.limit(perPage);
|
|
1840
|
+
builder.offset(offset);
|
|
1841
|
+
}
|
|
2082
1842
|
const { sql, params } = builder.build();
|
|
2083
1843
|
let total = 0;
|
|
2084
|
-
if (
|
|
1844
|
+
if (perPage !== void 0 && page !== void 0) {
|
|
2085
1845
|
const { sql: countSql, params: countParams } = countBuilder.build();
|
|
2086
1846
|
const countResult = await this.operations.executeQuery({
|
|
2087
1847
|
sql: countSql,
|
|
@@ -2096,7 +1856,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
|
|
|
2096
1856
|
} catch (error$1) {
|
|
2097
1857
|
throw new error.MastraError(
|
|
2098
1858
|
{
|
|
2099
|
-
id: "
|
|
1859
|
+
id: "CLOUDFLARE_D1_STORAGE_LIST_WORKFLOW_RUNS_ERROR",
|
|
2100
1860
|
domain: error.ErrorDomain.STORAGE,
|
|
2101
1861
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
2102
1862
|
text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
@@ -2158,7 +1918,7 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2158
1918
|
*/
|
|
2159
1919
|
constructor(config) {
|
|
2160
1920
|
try {
|
|
2161
|
-
super({ name: "D1" });
|
|
1921
|
+
super({ id: config.id, name: "D1" });
|
|
2162
1922
|
if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
|
|
2163
1923
|
throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
|
|
2164
1924
|
}
|
|
@@ -2212,12 +1972,6 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2212
1972
|
const scores = new ScoresStorageD1({
|
|
2213
1973
|
operations
|
|
2214
1974
|
});
|
|
2215
|
-
const legacyEvals = new LegacyEvalsStorageD1({
|
|
2216
|
-
operations
|
|
2217
|
-
});
|
|
2218
|
-
const traces = new TracesStorageD1({
|
|
2219
|
-
operations
|
|
2220
|
-
});
|
|
2221
1975
|
const workflows = new WorkflowsStorageD1({
|
|
2222
1976
|
operations
|
|
2223
1977
|
});
|
|
@@ -2227,8 +1981,6 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2227
1981
|
this.stores = {
|
|
2228
1982
|
operations,
|
|
2229
1983
|
scores,
|
|
2230
|
-
legacyEvals,
|
|
2231
|
-
traces,
|
|
2232
1984
|
workflows,
|
|
2233
1985
|
memory
|
|
2234
1986
|
};
|
|
@@ -2239,7 +1991,8 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2239
1991
|
resourceWorkingMemory: true,
|
|
2240
1992
|
hasColumn: true,
|
|
2241
1993
|
createTable: true,
|
|
2242
|
-
deleteMessages: false
|
|
1994
|
+
deleteMessages: false,
|
|
1995
|
+
listScoresBySpan: true
|
|
2243
1996
|
};
|
|
2244
1997
|
}
|
|
2245
1998
|
async createTable({
|
|
@@ -2279,15 +2032,6 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2279
2032
|
async getThreadById({ threadId }) {
|
|
2280
2033
|
return this.stores.memory.getThreadById({ threadId });
|
|
2281
2034
|
}
|
|
2282
|
-
/**
|
|
2283
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
2284
|
-
*/
|
|
2285
|
-
async getThreadsByResourceId({ resourceId }) {
|
|
2286
|
-
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2287
|
-
}
|
|
2288
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
2289
|
-
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2290
|
-
}
|
|
2291
2035
|
async saveThread({ thread }) {
|
|
2292
2036
|
return this.stores.memory.saveThread({ thread });
|
|
2293
2037
|
}
|
|
@@ -2304,34 +2048,14 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2304
2048
|
async saveMessages(args) {
|
|
2305
2049
|
return this.stores.memory.saveMessages(args);
|
|
2306
2050
|
}
|
|
2307
|
-
async getMessages({
|
|
2308
|
-
threadId,
|
|
2309
|
-
selectBy,
|
|
2310
|
-
format
|
|
2311
|
-
}) {
|
|
2312
|
-
return this.stores.memory.getMessages({ threadId, selectBy, format });
|
|
2313
|
-
}
|
|
2314
|
-
async getMessagesById({
|
|
2315
|
-
messageIds,
|
|
2316
|
-
format
|
|
2317
|
-
}) {
|
|
2318
|
-
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2319
|
-
}
|
|
2320
|
-
async getMessagesPaginated({
|
|
2321
|
-
threadId,
|
|
2322
|
-
selectBy,
|
|
2323
|
-
format
|
|
2324
|
-
}) {
|
|
2325
|
-
return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
|
|
2326
|
-
}
|
|
2327
2051
|
async updateWorkflowResults({
|
|
2328
2052
|
workflowName,
|
|
2329
2053
|
runId,
|
|
2330
2054
|
stepId,
|
|
2331
2055
|
result,
|
|
2332
|
-
|
|
2056
|
+
requestContext
|
|
2333
2057
|
}) {
|
|
2334
|
-
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result,
|
|
2058
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
2335
2059
|
}
|
|
2336
2060
|
async updateWorkflowState({
|
|
2337
2061
|
workflowName,
|
|
@@ -2351,15 +2075,8 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2351
2075
|
async loadWorkflowSnapshot(params) {
|
|
2352
2076
|
return this.stores.workflows.loadWorkflowSnapshot(params);
|
|
2353
2077
|
}
|
|
2354
|
-
async
|
|
2355
|
-
|
|
2356
|
-
fromDate,
|
|
2357
|
-
toDate,
|
|
2358
|
-
limit,
|
|
2359
|
-
offset,
|
|
2360
|
-
resourceId
|
|
2361
|
-
} = {}) {
|
|
2362
|
-
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2078
|
+
async listWorkflowRuns(args = {}) {
|
|
2079
|
+
return this.stores.workflows.listWorkflowRuns(args);
|
|
2363
2080
|
}
|
|
2364
2081
|
async getWorkflowRunById({
|
|
2365
2082
|
runId,
|
|
@@ -2375,24 +2092,6 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2375
2092
|
async batchInsert({ tableName, records }) {
|
|
2376
2093
|
return this.stores.operations.batchInsert({ tableName, records });
|
|
2377
2094
|
}
|
|
2378
|
-
/**
|
|
2379
|
-
* @deprecated use getTracesPaginated instead
|
|
2380
|
-
*/
|
|
2381
|
-
async getTraces(args) {
|
|
2382
|
-
return this.stores.traces.getTraces(args);
|
|
2383
|
-
}
|
|
2384
|
-
async getTracesPaginated(args) {
|
|
2385
|
-
return this.stores.traces.getTracesPaginated(args);
|
|
2386
|
-
}
|
|
2387
|
-
/**
|
|
2388
|
-
* @deprecated use getEvals instead
|
|
2389
|
-
*/
|
|
2390
|
-
async getEvalsByAgentName(agentName, type) {
|
|
2391
|
-
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2392
|
-
}
|
|
2393
|
-
async getEvals(options) {
|
|
2394
|
-
return this.stores.legacyEvals.getEvals(options);
|
|
2395
|
-
}
|
|
2396
2095
|
async updateMessages(_args) {
|
|
2397
2096
|
return this.stores.memory.updateMessages(_args);
|
|
2398
2097
|
}
|
|
@@ -2415,31 +2114,38 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
2415
2114
|
async saveScore(_score) {
|
|
2416
2115
|
return this.stores.scores.saveScore(_score);
|
|
2417
2116
|
}
|
|
2418
|
-
async
|
|
2117
|
+
async listScoresByRunId({
|
|
2419
2118
|
runId: _runId,
|
|
2420
2119
|
pagination: _pagination
|
|
2421
2120
|
}) {
|
|
2422
|
-
return this.stores.scores.
|
|
2121
|
+
return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
|
|
2423
2122
|
}
|
|
2424
|
-
async
|
|
2123
|
+
async listScoresByEntityId({
|
|
2425
2124
|
entityId: _entityId,
|
|
2426
2125
|
entityType: _entityType,
|
|
2427
2126
|
pagination: _pagination
|
|
2428
2127
|
}) {
|
|
2429
|
-
return this.stores.scores.
|
|
2128
|
+
return this.stores.scores.listScoresByEntityId({
|
|
2430
2129
|
entityId: _entityId,
|
|
2431
2130
|
entityType: _entityType,
|
|
2432
2131
|
pagination: _pagination
|
|
2433
2132
|
});
|
|
2434
2133
|
}
|
|
2435
|
-
async
|
|
2134
|
+
async listScoresByScorerId({
|
|
2436
2135
|
scorerId,
|
|
2437
2136
|
pagination,
|
|
2438
2137
|
entityId,
|
|
2439
2138
|
entityType,
|
|
2440
2139
|
source
|
|
2441
2140
|
}) {
|
|
2442
|
-
return this.stores.scores.
|
|
2141
|
+
return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
2142
|
+
}
|
|
2143
|
+
async listScoresBySpan({
|
|
2144
|
+
traceId,
|
|
2145
|
+
spanId,
|
|
2146
|
+
pagination
|
|
2147
|
+
}) {
|
|
2148
|
+
return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
|
|
2443
2149
|
}
|
|
2444
2150
|
/**
|
|
2445
2151
|
* Close the database connection
|