@mastra/cloudflare-d1 0.0.0-taofeeqInngest-20250603090617 → 0.0.0-tool-call-parts-20250630193309
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/_tsup-dts-rollup.d.cts +78 -38
- package/dist/_tsup-dts-rollup.d.ts +78 -38
- package/dist/index.cjs +728 -181
- package/dist/index.js +710 -163
- package/package.json +15 -14
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var agent = require('@mastra/core/agent');
|
|
4
|
+
var error = require('@mastra/core/error');
|
|
4
5
|
var storage = require('@mastra/core/storage');
|
|
5
6
|
var Cloudflare = require('cloudflare');
|
|
6
7
|
var utils = require('@mastra/core/utils');
|
|
@@ -256,27 +257,39 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
256
257
|
* @param config Configuration for D1 access (either REST API or Workers Binding API)
|
|
257
258
|
*/
|
|
258
259
|
constructor(config) {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
this.tablePrefix = config.tablePrefix || "";
|
|
264
|
-
if ("binding" in config) {
|
|
265
|
-
if (!config.binding) {
|
|
266
|
-
throw new Error("D1 binding is required when using Workers Binding API");
|
|
260
|
+
try {
|
|
261
|
+
super({ name: "D1" });
|
|
262
|
+
if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
|
|
263
|
+
throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
|
|
267
264
|
}
|
|
268
|
-
this.
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
265
|
+
this.tablePrefix = config.tablePrefix || "";
|
|
266
|
+
if ("binding" in config) {
|
|
267
|
+
if (!config.binding) {
|
|
268
|
+
throw new Error("D1 binding is required when using Workers Binding API");
|
|
269
|
+
}
|
|
270
|
+
this.binding = config.binding;
|
|
271
|
+
this.logger.info("Using D1 Workers Binding API");
|
|
272
|
+
} else {
|
|
273
|
+
if (!config.accountId || !config.databaseId || !config.apiToken) {
|
|
274
|
+
throw new Error("accountId, databaseId, and apiToken are required when using REST API");
|
|
275
|
+
}
|
|
276
|
+
this.accountId = config.accountId;
|
|
277
|
+
this.databaseId = config.databaseId;
|
|
278
|
+
this.client = new Cloudflare__default.default({
|
|
279
|
+
apiToken: config.apiToken
|
|
280
|
+
});
|
|
281
|
+
this.logger.info("Using D1 REST API");
|
|
273
282
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
283
|
+
} catch (error$1) {
|
|
284
|
+
throw new error.MastraError(
|
|
285
|
+
{
|
|
286
|
+
id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
|
|
287
|
+
domain: error.ErrorDomain.STORAGE,
|
|
288
|
+
category: error.ErrorCategory.SYSTEM,
|
|
289
|
+
text: "Error initializing D1Store"
|
|
290
|
+
},
|
|
291
|
+
error$1
|
|
292
|
+
);
|
|
280
293
|
}
|
|
281
294
|
}
|
|
282
295
|
// Helper method to get the full table name with prefix
|
|
@@ -389,34 +402,25 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
389
402
|
throw new Error(`D1 query error: ${error.message}`);
|
|
390
403
|
}
|
|
391
404
|
}
|
|
392
|
-
// Helper to
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
return
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
405
|
+
// Helper to get existing table columns
|
|
406
|
+
async getTableColumns(tableName) {
|
|
407
|
+
try {
|
|
408
|
+
const sql = `PRAGMA table_info(${tableName})`;
|
|
409
|
+
const result = await this.executeQuery({ sql, params: [] });
|
|
410
|
+
if (!result || !Array.isArray(result)) {
|
|
411
|
+
return [];
|
|
412
|
+
}
|
|
413
|
+
return result.map((row) => ({
|
|
414
|
+
name: row.name,
|
|
415
|
+
type: row.type
|
|
416
|
+
}));
|
|
417
|
+
} catch (error) {
|
|
418
|
+
this.logger.error(`Error getting table columns for ${tableName}:`, {
|
|
419
|
+
message: error instanceof Error ? error.message : String(error)
|
|
420
|
+
});
|
|
421
|
+
return [];
|
|
409
422
|
}
|
|
410
423
|
}
|
|
411
|
-
ensureDate(date) {
|
|
412
|
-
if (!date) return void 0;
|
|
413
|
-
return date instanceof Date ? date : new Date(date);
|
|
414
|
-
}
|
|
415
|
-
serializeDate(date) {
|
|
416
|
-
if (!date) return void 0;
|
|
417
|
-
const dateObj = this.ensureDate(date);
|
|
418
|
-
return dateObj?.toISOString();
|
|
419
|
-
}
|
|
420
424
|
// Helper to serialize objects to JSON strings
|
|
421
425
|
serializeValue(value) {
|
|
422
426
|
if (value === null || value === void 0) return null;
|
|
@@ -450,6 +454,18 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
450
454
|
}
|
|
451
455
|
return value;
|
|
452
456
|
}
|
|
457
|
+
getSqlType(type) {
|
|
458
|
+
switch (type) {
|
|
459
|
+
case "bigint":
|
|
460
|
+
return "INTEGER";
|
|
461
|
+
// SQLite uses INTEGER for all integer sizes
|
|
462
|
+
case "jsonb":
|
|
463
|
+
return "TEXT";
|
|
464
|
+
// Store JSON as TEXT in SQLite
|
|
465
|
+
default:
|
|
466
|
+
return super.getSqlType(type);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
453
469
|
async createTable({
|
|
454
470
|
tableName,
|
|
455
471
|
schema
|
|
@@ -465,16 +481,64 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
465
481
|
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
466
482
|
tableConstraints.push("UNIQUE (workflow_name, run_id)");
|
|
467
483
|
}
|
|
468
|
-
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
469
|
-
const { sql, params } = query.build();
|
|
470
484
|
try {
|
|
485
|
+
const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
|
|
486
|
+
const { sql, params } = query.build();
|
|
471
487
|
await this.executeQuery({ sql, params });
|
|
472
488
|
this.logger.debug(`Created table ${fullTableName}`);
|
|
473
|
-
} catch (error) {
|
|
489
|
+
} catch (error$1) {
|
|
474
490
|
this.logger.error(`Error creating table ${fullTableName}:`, {
|
|
475
|
-
message: error instanceof Error ? error.message : String(error)
|
|
491
|
+
message: error$1 instanceof Error ? error$1.message : String(error$1)
|
|
476
492
|
});
|
|
477
|
-
throw new
|
|
493
|
+
throw new error.MastraError(
|
|
494
|
+
{
|
|
495
|
+
id: "CLOUDFLARE_D1_STORAGE_CREATE_TABLE_ERROR",
|
|
496
|
+
domain: error.ErrorDomain.STORAGE,
|
|
497
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
498
|
+
text: `Failed to create table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
499
|
+
details: { tableName }
|
|
500
|
+
},
|
|
501
|
+
error$1
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Alters table schema to add columns if they don't exist
|
|
507
|
+
* @param tableName Name of the table
|
|
508
|
+
* @param schema Schema of the table
|
|
509
|
+
* @param ifNotExists Array of column names to add if they don't exist
|
|
510
|
+
*/
|
|
511
|
+
async alterTable({
|
|
512
|
+
tableName,
|
|
513
|
+
schema,
|
|
514
|
+
ifNotExists
|
|
515
|
+
}) {
|
|
516
|
+
const fullTableName = this.getTableName(tableName);
|
|
517
|
+
try {
|
|
518
|
+
const existingColumns = await this.getTableColumns(fullTableName);
|
|
519
|
+
const existingColumnNames = new Set(existingColumns.map((col) => col.name.toLowerCase()));
|
|
520
|
+
for (const columnName of ifNotExists) {
|
|
521
|
+
if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
|
|
522
|
+
const columnDef = schema[columnName];
|
|
523
|
+
const sqlType = this.getSqlType(columnDef.type);
|
|
524
|
+
const nullable = columnDef.nullable === false ? "NOT NULL" : "";
|
|
525
|
+
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
|
|
526
|
+
const alterSql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${nullable} ${defaultValue}`.trim();
|
|
527
|
+
await this.executeQuery({ sql: alterSql, params: [] });
|
|
528
|
+
this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
} catch (error$1) {
|
|
532
|
+
throw new error.MastraError(
|
|
533
|
+
{
|
|
534
|
+
id: "CLOUDFLARE_D1_STORAGE_ALTER_TABLE_ERROR",
|
|
535
|
+
domain: error.ErrorDomain.STORAGE,
|
|
536
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
537
|
+
text: `Failed to alter table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
538
|
+
details: { tableName }
|
|
539
|
+
},
|
|
540
|
+
error$1
|
|
541
|
+
);
|
|
478
542
|
}
|
|
479
543
|
}
|
|
480
544
|
async clearTable({ tableName }) {
|
|
@@ -484,11 +548,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
484
548
|
const { sql, params } = query.build();
|
|
485
549
|
await this.executeQuery({ sql, params });
|
|
486
550
|
this.logger.debug(`Cleared table ${fullTableName}`);
|
|
487
|
-
} catch (error) {
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
551
|
+
} catch (error$1) {
|
|
552
|
+
throw new error.MastraError(
|
|
553
|
+
{
|
|
554
|
+
id: "CLOUDFLARE_D1_STORAGE_CLEAR_TABLE_ERROR",
|
|
555
|
+
domain: error.ErrorDomain.STORAGE,
|
|
556
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
557
|
+
text: `Failed to clear table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
558
|
+
details: { tableName }
|
|
559
|
+
},
|
|
560
|
+
error$1
|
|
561
|
+
);
|
|
492
562
|
}
|
|
493
563
|
}
|
|
494
564
|
async processRecord(record) {
|
|
@@ -507,10 +577,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
507
577
|
const { sql, params } = query.build();
|
|
508
578
|
try {
|
|
509
579
|
await this.executeQuery({ sql, params });
|
|
510
|
-
} catch (error) {
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
580
|
+
} catch (error$1) {
|
|
581
|
+
throw new error.MastraError(
|
|
582
|
+
{
|
|
583
|
+
id: "CLOUDFLARE_D1_STORAGE_INSERT_ERROR",
|
|
584
|
+
domain: error.ErrorDomain.STORAGE,
|
|
585
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
586
|
+
text: `Failed to insert into ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
587
|
+
details: { tableName }
|
|
588
|
+
},
|
|
589
|
+
error$1
|
|
590
|
+
);
|
|
514
591
|
}
|
|
515
592
|
}
|
|
516
593
|
async load({ tableName, keys }) {
|
|
@@ -535,11 +612,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
535
612
|
processedResult[key] = this.deserializeValue(value);
|
|
536
613
|
}
|
|
537
614
|
return processedResult;
|
|
538
|
-
} catch (error) {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
615
|
+
} catch (error$1) {
|
|
616
|
+
throw new error.MastraError(
|
|
617
|
+
{
|
|
618
|
+
id: "CLOUDFLARE_D1_STORAGE_LOAD_ERROR",
|
|
619
|
+
domain: error.ErrorDomain.STORAGE,
|
|
620
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
621
|
+
text: `Failed to load from ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
622
|
+
details: { tableName }
|
|
623
|
+
},
|
|
624
|
+
error$1
|
|
625
|
+
);
|
|
543
626
|
}
|
|
544
627
|
}
|
|
545
628
|
async getThreadById({ threadId }) {
|
|
@@ -555,13 +638,25 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
555
638
|
updatedAt: this.ensureDate(thread.updatedAt),
|
|
556
639
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
557
640
|
};
|
|
558
|
-
} catch (error) {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
641
|
+
} catch (error$1) {
|
|
642
|
+
const mastraError = new error.MastraError(
|
|
643
|
+
{
|
|
644
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
|
|
645
|
+
domain: error.ErrorDomain.STORAGE,
|
|
646
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
647
|
+
text: `Error processing thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
648
|
+
details: { threadId }
|
|
649
|
+
},
|
|
650
|
+
error$1
|
|
651
|
+
);
|
|
652
|
+
this.logger?.error(mastraError.toString());
|
|
653
|
+
this.logger?.trackException(mastraError);
|
|
562
654
|
return null;
|
|
563
655
|
}
|
|
564
656
|
}
|
|
657
|
+
/**
|
|
658
|
+
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
659
|
+
*/
|
|
565
660
|
async getThreadsByResourceId({ resourceId }) {
|
|
566
661
|
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
567
662
|
try {
|
|
@@ -574,13 +669,67 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
574
669
|
updatedAt: this.ensureDate(thread.updatedAt),
|
|
575
670
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
|
|
576
671
|
}));
|
|
577
|
-
} catch (error) {
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
672
|
+
} catch (error$1) {
|
|
673
|
+
const mastraError = new error.MastraError(
|
|
674
|
+
{
|
|
675
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
|
|
676
|
+
domain: error.ErrorDomain.STORAGE,
|
|
677
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
678
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
679
|
+
details: { resourceId }
|
|
680
|
+
},
|
|
681
|
+
error$1
|
|
682
|
+
);
|
|
683
|
+
this.logger?.error(mastraError.toString());
|
|
684
|
+
this.logger?.trackException(mastraError);
|
|
581
685
|
return [];
|
|
582
686
|
}
|
|
583
687
|
}
|
|
688
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
689
|
+
const { resourceId, page, perPage } = args;
|
|
690
|
+
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
691
|
+
const mapRowToStorageThreadType = (row) => ({
|
|
692
|
+
...row,
|
|
693
|
+
createdAt: this.ensureDate(row.createdAt),
|
|
694
|
+
updatedAt: this.ensureDate(row.updatedAt),
|
|
695
|
+
metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
|
|
696
|
+
});
|
|
697
|
+
try {
|
|
698
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
|
|
699
|
+
const countResult = await this.executeQuery(countQuery.build());
|
|
700
|
+
const total = Number(countResult?.[0]?.count ?? 0);
|
|
701
|
+
const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
|
|
702
|
+
const results = await this.executeQuery(selectQuery.build());
|
|
703
|
+
const threads = results.map(mapRowToStorageThreadType);
|
|
704
|
+
return {
|
|
705
|
+
threads,
|
|
706
|
+
total,
|
|
707
|
+
page,
|
|
708
|
+
perPage,
|
|
709
|
+
hasMore: page * perPage + threads.length < total
|
|
710
|
+
};
|
|
711
|
+
} catch (error$1) {
|
|
712
|
+
const mastraError = new error.MastraError(
|
|
713
|
+
{
|
|
714
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
|
|
715
|
+
domain: error.ErrorDomain.STORAGE,
|
|
716
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
717
|
+
text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
718
|
+
details: { resourceId }
|
|
719
|
+
},
|
|
720
|
+
error$1
|
|
721
|
+
);
|
|
722
|
+
this.logger?.error(mastraError.toString());
|
|
723
|
+
this.logger?.trackException(mastraError);
|
|
724
|
+
return {
|
|
725
|
+
threads: [],
|
|
726
|
+
total: 0,
|
|
727
|
+
page,
|
|
728
|
+
perPage,
|
|
729
|
+
hasMore: false
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
}
|
|
584
733
|
async saveThread({ thread }) {
|
|
585
734
|
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
586
735
|
const threadToSave = {
|
|
@@ -606,10 +755,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
606
755
|
try {
|
|
607
756
|
await this.executeQuery({ sql, params });
|
|
608
757
|
return thread;
|
|
609
|
-
} catch (error) {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
758
|
+
} catch (error$1) {
|
|
759
|
+
throw new error.MastraError(
|
|
760
|
+
{
|
|
761
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
|
|
762
|
+
domain: error.ErrorDomain.STORAGE,
|
|
763
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
764
|
+
text: `Failed to save thread to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
765
|
+
details: { threadId: thread.id }
|
|
766
|
+
},
|
|
767
|
+
error$1
|
|
768
|
+
);
|
|
613
769
|
}
|
|
614
770
|
}
|
|
615
771
|
async updateThread({
|
|
@@ -618,19 +774,19 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
618
774
|
metadata
|
|
619
775
|
}) {
|
|
620
776
|
const thread = await this.getThreadById({ threadId: id });
|
|
621
|
-
if (!thread) {
|
|
622
|
-
throw new Error(`Thread ${id} not found`);
|
|
623
|
-
}
|
|
624
|
-
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
625
|
-
const mergedMetadata = {
|
|
626
|
-
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
627
|
-
...metadata
|
|
628
|
-
};
|
|
629
|
-
const columns = ["title", "metadata", "updatedAt"];
|
|
630
|
-
const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
|
|
631
|
-
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
632
|
-
const { sql, params } = query.build();
|
|
633
777
|
try {
|
|
778
|
+
if (!thread) {
|
|
779
|
+
throw new Error(`Thread ${id} not found`);
|
|
780
|
+
}
|
|
781
|
+
const fullTableName = this.getTableName(storage.TABLE_THREADS);
|
|
782
|
+
const mergedMetadata = {
|
|
783
|
+
...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
784
|
+
...metadata
|
|
785
|
+
};
|
|
786
|
+
const columns = ["title", "metadata", "updatedAt"];
|
|
787
|
+
const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
|
|
788
|
+
const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
|
|
789
|
+
const { sql, params } = query.build();
|
|
634
790
|
await this.executeQuery({ sql, params });
|
|
635
791
|
return {
|
|
636
792
|
...thread,
|
|
@@ -641,10 +797,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
641
797
|
},
|
|
642
798
|
updatedAt: /* @__PURE__ */ new Date()
|
|
643
799
|
};
|
|
644
|
-
} catch (error) {
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
800
|
+
} catch (error$1) {
|
|
801
|
+
throw new error.MastraError(
|
|
802
|
+
{
|
|
803
|
+
id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
|
|
804
|
+
domain: error.ErrorDomain.STORAGE,
|
|
805
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
806
|
+
text: `Failed to update thread ${id}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
807
|
+
details: { threadId: id }
|
|
808
|
+
},
|
|
809
|
+
error$1
|
|
810
|
+
);
|
|
648
811
|
}
|
|
649
812
|
}
|
|
650
813
|
async deleteThread({ threadId }) {
|
|
@@ -657,11 +820,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
657
820
|
const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
|
|
658
821
|
const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
|
|
659
822
|
await this.executeQuery({ sql: messagesSql, params: messagesParams });
|
|
660
|
-
} catch (error) {
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
823
|
+
} catch (error$1) {
|
|
824
|
+
throw new error.MastraError(
|
|
825
|
+
{
|
|
826
|
+
id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
|
|
827
|
+
domain: error.ErrorDomain.STORAGE,
|
|
828
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
829
|
+
text: `Failed to delete thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
830
|
+
details: { threadId }
|
|
831
|
+
},
|
|
832
|
+
error$1
|
|
833
|
+
);
|
|
665
834
|
}
|
|
666
835
|
}
|
|
667
836
|
async saveMessages(args) {
|
|
@@ -669,6 +838,7 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
669
838
|
if (messages.length === 0) return [];
|
|
670
839
|
try {
|
|
671
840
|
const now = /* @__PURE__ */ new Date();
|
|
841
|
+
const threadId = messages[0]?.threadId;
|
|
672
842
|
for (const [i, message] of messages.entries()) {
|
|
673
843
|
if (!message.id) throw new Error(`Message at index ${i} missing id`);
|
|
674
844
|
if (!message.threadId) throw new Error(`Message at index ${i} missing threadId`);
|
|
@@ -687,42 +857,49 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
687
857
|
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
688
858
|
createdAt: createdAt.toISOString(),
|
|
689
859
|
role: message.role,
|
|
690
|
-
type: message.type || "v2"
|
|
860
|
+
type: message.type || "v2",
|
|
861
|
+
resourceId: message.resourceId
|
|
691
862
|
};
|
|
692
863
|
});
|
|
693
|
-
await
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
864
|
+
await Promise.all([
|
|
865
|
+
this.batchUpsert({
|
|
866
|
+
tableName: storage.TABLE_MESSAGES,
|
|
867
|
+
records: messagesToInsert
|
|
868
|
+
}),
|
|
869
|
+
// Update thread's updatedAt timestamp
|
|
870
|
+
this.executeQuery({
|
|
871
|
+
sql: `UPDATE ${this.getTableName(storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
|
|
872
|
+
params: [now.toISOString(), threadId]
|
|
873
|
+
})
|
|
874
|
+
]);
|
|
697
875
|
this.logger.debug(`Saved ${messages.length} messages`);
|
|
698
876
|
const list = new agent.MessageList().add(messages, "memory");
|
|
699
877
|
if (format === `v2`) return list.get.all.v2();
|
|
700
878
|
return list.get.all.v1();
|
|
701
|
-
} catch (error) {
|
|
702
|
-
|
|
703
|
-
|
|
879
|
+
} catch (error$1) {
|
|
880
|
+
throw new error.MastraError(
|
|
881
|
+
{
|
|
882
|
+
id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
|
|
883
|
+
domain: error.ErrorDomain.STORAGE,
|
|
884
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
885
|
+
text: `Failed to save messages: ${error$1 instanceof Error ? error$1.message : String(error$1)}`
|
|
886
|
+
},
|
|
887
|
+
error$1
|
|
888
|
+
);
|
|
704
889
|
}
|
|
705
890
|
}
|
|
706
|
-
async
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
const
|
|
712
|
-
const
|
|
713
|
-
const include = selectBy?.include || [];
|
|
714
|
-
const messages = [];
|
|
715
|
-
try {
|
|
716
|
-
if (include.length) {
|
|
717
|
-
const prevMax = Math.max(...include.map((i) => i.withPreviousMessages || 0));
|
|
718
|
-
const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
|
|
719
|
-
const includeIds = include.map((i) => i.id);
|
|
720
|
-
const sql2 = `
|
|
891
|
+
async _getIncludedMessages(threadId, selectBy) {
|
|
892
|
+
const include = selectBy?.include;
|
|
893
|
+
if (!include) return null;
|
|
894
|
+
const prevMax = Math.max(...include.map((i) => i.withPreviousMessages || 0));
|
|
895
|
+
const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
|
|
896
|
+
const includeIds = include.map((i) => i.id);
|
|
897
|
+
const sql = `
|
|
721
898
|
WITH ordered_messages AS (
|
|
722
899
|
SELECT
|
|
723
900
|
*,
|
|
724
901
|
ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
|
|
725
|
-
FROM ${
|
|
902
|
+
FROM ${this.getTableName(storage.TABLE_MESSAGES)}
|
|
726
903
|
WHERE thread_id = ?
|
|
727
904
|
)
|
|
728
905
|
SELECT
|
|
@@ -745,20 +922,38 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
745
922
|
)
|
|
746
923
|
ORDER BY m.createdAt DESC
|
|
747
924
|
`;
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
925
|
+
const params = [
|
|
926
|
+
threadId,
|
|
927
|
+
...includeIds,
|
|
928
|
+
// for m.id IN (...)
|
|
929
|
+
...includeIds,
|
|
930
|
+
// for target.id IN (...)
|
|
931
|
+
prevMax,
|
|
932
|
+
nextMax
|
|
933
|
+
];
|
|
934
|
+
const messages = await this.executeQuery({ sql, params });
|
|
935
|
+
return messages;
|
|
936
|
+
}
|
|
937
|
+
async getMessages({
|
|
938
|
+
threadId,
|
|
939
|
+
selectBy,
|
|
940
|
+
format
|
|
941
|
+
}) {
|
|
942
|
+
const fullTableName = this.getTableName(storage.TABLE_MESSAGES);
|
|
943
|
+
const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
944
|
+
const include = selectBy?.include || [];
|
|
945
|
+
const messages = [];
|
|
946
|
+
try {
|
|
947
|
+
if (include.length) {
|
|
948
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
758
949
|
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
759
950
|
}
|
|
760
951
|
const excludeIds = messages.map((m) => m.id);
|
|
761
|
-
|
|
952
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
953
|
+
if (excludeIds.length > 0) {
|
|
954
|
+
query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
|
|
955
|
+
}
|
|
956
|
+
query.orderBy("createdAt", "DESC").limit(limit);
|
|
762
957
|
const { sql, params } = query.build();
|
|
763
958
|
const result = await this.executeQuery({ sql, params });
|
|
764
959
|
if (Array.isArray(result)) messages.push(...result);
|
|
@@ -781,12 +976,83 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
781
976
|
const list = new agent.MessageList().add(processedMessages, "memory");
|
|
782
977
|
if (format === `v2`) return list.get.all.v2();
|
|
783
978
|
return list.get.all.v1();
|
|
784
|
-
} catch (error) {
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
979
|
+
} catch (error$1) {
|
|
980
|
+
const mastraError = new error.MastraError(
|
|
981
|
+
{
|
|
982
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
|
|
983
|
+
domain: error.ErrorDomain.STORAGE,
|
|
984
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
985
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
986
|
+
details: { threadId }
|
|
987
|
+
},
|
|
988
|
+
error$1
|
|
989
|
+
);
|
|
990
|
+
this.logger?.error(mastraError.toString());
|
|
991
|
+
this.logger?.trackException(mastraError);
|
|
992
|
+
throw mastraError;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
async getMessagesPaginated({
|
|
996
|
+
threadId,
|
|
997
|
+
selectBy,
|
|
998
|
+
format
|
|
999
|
+
}) {
|
|
1000
|
+
const { dateRange, page = 0, perPage = 40 } = selectBy?.pagination || {};
|
|
1001
|
+
const { start: fromDate, end: toDate } = dateRange || {};
|
|
1002
|
+
const fullTableName = this.getTableName(storage.TABLE_MESSAGES);
|
|
1003
|
+
const messages = [];
|
|
1004
|
+
try {
|
|
1005
|
+
if (selectBy?.include?.length) {
|
|
1006
|
+
const includeResult = await this._getIncludedMessages(threadId, selectBy);
|
|
1007
|
+
if (Array.isArray(includeResult)) messages.push(...includeResult);
|
|
1008
|
+
}
|
|
1009
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
|
|
1010
|
+
if (fromDate) {
|
|
1011
|
+
countQuery.andWhere("createdAt >= ?", this.serializeDate(fromDate));
|
|
1012
|
+
}
|
|
1013
|
+
if (toDate) {
|
|
1014
|
+
countQuery.andWhere("createdAt <= ?", this.serializeDate(toDate));
|
|
1015
|
+
}
|
|
1016
|
+
const countResult = await this.executeQuery(countQuery.build());
|
|
1017
|
+
const total = Number(countResult[0]?.count ?? 0);
|
|
1018
|
+
const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
|
|
1019
|
+
if (fromDate) {
|
|
1020
|
+
query.andWhere("createdAt >= ?", this.serializeDate(fromDate));
|
|
1021
|
+
}
|
|
1022
|
+
if (toDate) {
|
|
1023
|
+
query.andWhere("createdAt <= ?", this.serializeDate(toDate));
|
|
1024
|
+
}
|
|
1025
|
+
query.orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
|
|
1026
|
+
const results = await this.executeQuery(query.build());
|
|
1027
|
+
const list = new agent.MessageList().add(results, "memory");
|
|
1028
|
+
messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
|
|
1029
|
+
return {
|
|
1030
|
+
messages,
|
|
1031
|
+
total,
|
|
1032
|
+
page,
|
|
1033
|
+
perPage,
|
|
1034
|
+
hasMore: page * perPage + messages.length < total
|
|
1035
|
+
};
|
|
1036
|
+
} catch (error$1) {
|
|
1037
|
+
const mastraError = new error.MastraError(
|
|
1038
|
+
{
|
|
1039
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
|
|
1040
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1041
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1042
|
+
text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1043
|
+
details: { threadId }
|
|
1044
|
+
},
|
|
1045
|
+
error$1
|
|
1046
|
+
);
|
|
1047
|
+
this.logger?.error(mastraError.toString());
|
|
1048
|
+
this.logger?.trackException(mastraError);
|
|
1049
|
+
return {
|
|
1050
|
+
messages: [],
|
|
1051
|
+
total: 0,
|
|
1052
|
+
page,
|
|
1053
|
+
perPage,
|
|
1054
|
+
hasMore: false
|
|
1055
|
+
};
|
|
790
1056
|
}
|
|
791
1057
|
}
|
|
792
1058
|
async persistWorkflowSnapshot({
|
|
@@ -823,24 +1089,43 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
823
1089
|
const { sql, params } = query.build();
|
|
824
1090
|
try {
|
|
825
1091
|
await this.executeQuery({ sql, params });
|
|
826
|
-
} catch (error) {
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
1092
|
+
} catch (error$1) {
|
|
1093
|
+
throw new error.MastraError(
|
|
1094
|
+
{
|
|
1095
|
+
id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
|
|
1096
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1097
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1098
|
+
text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1099
|
+
details: { workflowName, runId }
|
|
1100
|
+
},
|
|
1101
|
+
error$1
|
|
1102
|
+
);
|
|
831
1103
|
}
|
|
832
1104
|
}
|
|
833
1105
|
async loadWorkflowSnapshot(params) {
|
|
834
1106
|
const { workflowName, runId } = params;
|
|
835
1107
|
this.logger.debug("Loading workflow snapshot", { workflowName, runId });
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
1108
|
+
try {
|
|
1109
|
+
const d = await this.load({
|
|
1110
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
1111
|
+
keys: {
|
|
1112
|
+
workflow_name: workflowName,
|
|
1113
|
+
run_id: runId
|
|
1114
|
+
}
|
|
1115
|
+
});
|
|
1116
|
+
return d ? d.snapshot : null;
|
|
1117
|
+
} catch (error$1) {
|
|
1118
|
+
throw new error.MastraError(
|
|
1119
|
+
{
|
|
1120
|
+
id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
|
|
1121
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1122
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1123
|
+
text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1124
|
+
details: { workflowName, runId }
|
|
1125
|
+
},
|
|
1126
|
+
error$1
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
844
1129
|
}
|
|
845
1130
|
/**
|
|
846
1131
|
* Insert multiple records in a batch operation
|
|
@@ -874,13 +1159,77 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
874
1159
|
);
|
|
875
1160
|
}
|
|
876
1161
|
this.logger.debug(`Successfully batch inserted ${records.length} records into ${tableName}`);
|
|
877
|
-
} catch (error) {
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
1162
|
+
} catch (error$1) {
|
|
1163
|
+
throw new error.MastraError(
|
|
1164
|
+
{
|
|
1165
|
+
id: "CLOUDFLARE_D1_STORAGE_BATCH_INSERT_ERROR",
|
|
1166
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1167
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1168
|
+
text: `Failed to batch insert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1169
|
+
details: { tableName }
|
|
1170
|
+
},
|
|
1171
|
+
error$1
|
|
1172
|
+
);
|
|
882
1173
|
}
|
|
883
1174
|
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Upsert multiple records in a batch operation
|
|
1177
|
+
* @param tableName The table to insert into
|
|
1178
|
+
* @param records The records to insert
|
|
1179
|
+
*/
|
|
1180
|
+
async batchUpsert({
|
|
1181
|
+
tableName,
|
|
1182
|
+
records
|
|
1183
|
+
}) {
|
|
1184
|
+
if (records.length === 0) return;
|
|
1185
|
+
const fullTableName = this.getTableName(tableName);
|
|
1186
|
+
try {
|
|
1187
|
+
const batchSize = 50;
|
|
1188
|
+
for (let i = 0; i < records.length; i += batchSize) {
|
|
1189
|
+
const batch = records.slice(i, i + batchSize);
|
|
1190
|
+
const recordsToInsert = batch;
|
|
1191
|
+
if (recordsToInsert.length > 0) {
|
|
1192
|
+
const firstRecord = recordsToInsert[0];
|
|
1193
|
+
const columns = Object.keys(firstRecord || {});
|
|
1194
|
+
for (const record of recordsToInsert) {
|
|
1195
|
+
const values = columns.map((col) => {
|
|
1196
|
+
if (!record) return null;
|
|
1197
|
+
const value = typeof col === "string" ? record[col] : null;
|
|
1198
|
+
return this.serializeValue(value);
|
|
1199
|
+
});
|
|
1200
|
+
const recordToUpsert = columns.reduce(
|
|
1201
|
+
(acc, col) => {
|
|
1202
|
+
if (col !== "createdAt") acc[col] = `excluded.${col}`;
|
|
1203
|
+
return acc;
|
|
1204
|
+
},
|
|
1205
|
+
{}
|
|
1206
|
+
);
|
|
1207
|
+
const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], recordToUpsert);
|
|
1208
|
+
const { sql, params } = query.build();
|
|
1209
|
+
await this.executeQuery({ sql, params });
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
this.logger.debug(
|
|
1213
|
+
`Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
this.logger.debug(`Successfully batch upserted ${records.length} records into ${tableName}`);
|
|
1217
|
+
} catch (error$1) {
|
|
1218
|
+
throw new error.MastraError(
|
|
1219
|
+
{
|
|
1220
|
+
id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
|
|
1221
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1222
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1223
|
+
text: `Failed to batch upsert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1224
|
+
details: { tableName }
|
|
1225
|
+
},
|
|
1226
|
+
error$1
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* @deprecated use getTracesPaginated instead
|
|
1232
|
+
*/
|
|
884
1233
|
async getTraces({
|
|
885
1234
|
name,
|
|
886
1235
|
scope,
|
|
@@ -910,22 +1259,108 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
910
1259
|
if (toDate) {
|
|
911
1260
|
query.andWhere("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
|
|
912
1261
|
}
|
|
913
|
-
query.orderBy("startTime", "DESC").limit(perPage).offset(
|
|
1262
|
+
query.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
|
|
914
1263
|
const { sql, params } = query.build();
|
|
915
1264
|
const results = await this.executeQuery({ sql, params });
|
|
916
|
-
return isArrayOfRecords(results) ? results.map(
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
1265
|
+
return isArrayOfRecords(results) ? results.map(
|
|
1266
|
+
(trace) => ({
|
|
1267
|
+
...trace,
|
|
1268
|
+
attributes: this.deserializeValue(trace.attributes, "jsonb"),
|
|
1269
|
+
status: this.deserializeValue(trace.status, "jsonb"),
|
|
1270
|
+
events: this.deserializeValue(trace.events, "jsonb"),
|
|
1271
|
+
links: this.deserializeValue(trace.links, "jsonb"),
|
|
1272
|
+
other: this.deserializeValue(trace.other, "jsonb")
|
|
1273
|
+
})
|
|
1274
|
+
) : [];
|
|
1275
|
+
} catch (error$1) {
|
|
1276
|
+
const mastraError = new error.MastraError(
|
|
1277
|
+
{
|
|
1278
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
|
|
1279
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1280
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1281
|
+
text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1282
|
+
details: {
|
|
1283
|
+
name: name ?? "",
|
|
1284
|
+
scope: scope ?? ""
|
|
1285
|
+
}
|
|
1286
|
+
},
|
|
1287
|
+
error$1
|
|
1288
|
+
);
|
|
1289
|
+
this.logger?.error(mastraError.toString());
|
|
1290
|
+
this.logger?.trackException(mastraError);
|
|
926
1291
|
return [];
|
|
927
1292
|
}
|
|
928
1293
|
}
|
|
1294
|
+
async getTracesPaginated(args) {
|
|
1295
|
+
const { name, scope, page, perPage, attributes, fromDate, toDate } = args;
|
|
1296
|
+
const fullTableName = this.getTableName(storage.TABLE_TRACES);
|
|
1297
|
+
try {
|
|
1298
|
+
const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
|
|
1299
|
+
const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
|
|
1300
|
+
if (name) {
|
|
1301
|
+
dataQuery.andWhere("name LIKE ?", `%${name}%`);
|
|
1302
|
+
countQuery.andWhere("name LIKE ?", `%${name}%`);
|
|
1303
|
+
}
|
|
1304
|
+
if (scope) {
|
|
1305
|
+
dataQuery.andWhere("scope = ?", scope);
|
|
1306
|
+
countQuery.andWhere("scope = ?", scope);
|
|
1307
|
+
}
|
|
1308
|
+
if (attributes && Object.keys(attributes).length > 0) {
|
|
1309
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
1310
|
+
dataQuery.jsonLike("attributes", key, value);
|
|
1311
|
+
countQuery.jsonLike("attributes", key, value);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
if (fromDate) {
|
|
1315
|
+
const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
|
|
1316
|
+
dataQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1317
|
+
countQuery.andWhere("createdAt >= ?", fromDateStr);
|
|
1318
|
+
}
|
|
1319
|
+
if (toDate) {
|
|
1320
|
+
const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
|
|
1321
|
+
dataQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1322
|
+
countQuery.andWhere("createdAt <= ?", toDateStr);
|
|
1323
|
+
}
|
|
1324
|
+
const countResult = await this.executeQuery(countQuery.build());
|
|
1325
|
+
const total = Number(countResult?.[0]?.count ?? 0);
|
|
1326
|
+
dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
|
|
1327
|
+
const results = await this.executeQuery(dataQuery.build());
|
|
1328
|
+
const traces = isArrayOfRecords(results) ? results.map(
|
|
1329
|
+
(trace) => ({
|
|
1330
|
+
...trace,
|
|
1331
|
+
attributes: this.deserializeValue(trace.attributes, "jsonb"),
|
|
1332
|
+
status: this.deserializeValue(trace.status, "jsonb"),
|
|
1333
|
+
events: this.deserializeValue(trace.events, "jsonb"),
|
|
1334
|
+
links: this.deserializeValue(trace.links, "jsonb"),
|
|
1335
|
+
other: this.deserializeValue(trace.other, "jsonb")
|
|
1336
|
+
})
|
|
1337
|
+
) : [];
|
|
1338
|
+
return {
|
|
1339
|
+
traces,
|
|
1340
|
+
total,
|
|
1341
|
+
page,
|
|
1342
|
+
perPage,
|
|
1343
|
+
hasMore: page * perPage + traces.length < total
|
|
1344
|
+
};
|
|
1345
|
+
} catch (error$1) {
|
|
1346
|
+
const mastraError = new error.MastraError(
|
|
1347
|
+
{
|
|
1348
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
|
|
1349
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1350
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1351
|
+
text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1352
|
+
details: { name: name ?? "", scope: scope ?? "" }
|
|
1353
|
+
},
|
|
1354
|
+
error$1
|
|
1355
|
+
);
|
|
1356
|
+
this.logger?.error(mastraError.toString());
|
|
1357
|
+
this.logger?.trackException(mastraError);
|
|
1358
|
+
return { traces: [], total: 0, page, perPage, hasMore: false };
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* @deprecated use getEvals instead
|
|
1363
|
+
*/
|
|
929
1364
|
async getEvalsByAgentName(agentName, type) {
|
|
930
1365
|
const fullTableName = this.getTableName(storage.TABLE_EVALS);
|
|
931
1366
|
try {
|
|
@@ -954,13 +1389,109 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
954
1389
|
testInfo
|
|
955
1390
|
};
|
|
956
1391
|
}) : [];
|
|
957
|
-
} catch (error) {
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
1392
|
+
} catch (error$1) {
|
|
1393
|
+
const mastraError = new error.MastraError(
|
|
1394
|
+
{
|
|
1395
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
1396
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1397
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1398
|
+
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1399
|
+
details: { agentName }
|
|
1400
|
+
},
|
|
1401
|
+
error$1
|
|
1402
|
+
);
|
|
1403
|
+
this.logger?.error(mastraError.toString());
|
|
1404
|
+
this.logger?.trackException(mastraError);
|
|
961
1405
|
return [];
|
|
962
1406
|
}
|
|
963
1407
|
}
|
|
1408
|
+
async getEvals(options) {
|
|
1409
|
+
const { agentName, type, page = 0, perPage = 40, fromDate, toDate } = options || {};
|
|
1410
|
+
const fullTableName = this.getTableName(storage.TABLE_EVALS);
|
|
1411
|
+
const conditions = [];
|
|
1412
|
+
const queryParams = [];
|
|
1413
|
+
if (agentName) {
|
|
1414
|
+
conditions.push(`agent_name = ?`);
|
|
1415
|
+
queryParams.push(agentName);
|
|
1416
|
+
}
|
|
1417
|
+
if (type === "test") {
|
|
1418
|
+
conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
|
|
1419
|
+
} else if (type === "live") {
|
|
1420
|
+
conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
|
|
1421
|
+
}
|
|
1422
|
+
if (fromDate) {
|
|
1423
|
+
conditions.push(`createdAt >= ?`);
|
|
1424
|
+
queryParams.push(this.serializeDate(fromDate));
|
|
1425
|
+
}
|
|
1426
|
+
if (toDate) {
|
|
1427
|
+
conditions.push(`createdAt <= ?`);
|
|
1428
|
+
queryParams.push(this.serializeDate(toDate));
|
|
1429
|
+
}
|
|
1430
|
+
const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
|
|
1431
|
+
if (conditions.length > 0) {
|
|
1432
|
+
countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
1433
|
+
}
|
|
1434
|
+
const { sql: countSql, params: countParams } = countQueryBuilder.build();
|
|
1435
|
+
try {
|
|
1436
|
+
const countResult = await this.executeQuery({ sql: countSql, params: countParams, first: true });
|
|
1437
|
+
const total = Number(countResult?.count || 0);
|
|
1438
|
+
const currentOffset = page * perPage;
|
|
1439
|
+
if (total === 0) {
|
|
1440
|
+
return {
|
|
1441
|
+
evals: [],
|
|
1442
|
+
total: 0,
|
|
1443
|
+
page,
|
|
1444
|
+
perPage,
|
|
1445
|
+
hasMore: false
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
|
|
1449
|
+
if (conditions.length > 0) {
|
|
1450
|
+
dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
|
|
1451
|
+
}
|
|
1452
|
+
dataQueryBuilder.orderBy("createdAt", "DESC").limit(perPage).offset(currentOffset);
|
|
1453
|
+
const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
|
|
1454
|
+
const rows = await this.executeQuery({ sql: dataSql, params: dataParams });
|
|
1455
|
+
const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
|
|
1456
|
+
const result = this.deserializeValue(row.result);
|
|
1457
|
+
const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
|
|
1458
|
+
if (!result || typeof result !== "object" || !("score" in result)) {
|
|
1459
|
+
throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
|
|
1460
|
+
}
|
|
1461
|
+
return {
|
|
1462
|
+
input: row.input,
|
|
1463
|
+
output: row.output,
|
|
1464
|
+
result,
|
|
1465
|
+
agentName: row.agent_name,
|
|
1466
|
+
metricName: row.metric_name,
|
|
1467
|
+
instructions: row.instructions,
|
|
1468
|
+
testInfo,
|
|
1469
|
+
globalRunId: row.global_run_id,
|
|
1470
|
+
runId: row.run_id,
|
|
1471
|
+
createdAt: row.createdAt
|
|
1472
|
+
};
|
|
1473
|
+
});
|
|
1474
|
+
const hasMore = currentOffset + evals.length < total;
|
|
1475
|
+
return {
|
|
1476
|
+
evals,
|
|
1477
|
+
total,
|
|
1478
|
+
page,
|
|
1479
|
+
perPage,
|
|
1480
|
+
hasMore
|
|
1481
|
+
};
|
|
1482
|
+
} catch (error$1) {
|
|
1483
|
+
throw new error.MastraError(
|
|
1484
|
+
{
|
|
1485
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
|
|
1486
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1487
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1488
|
+
text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1489
|
+
details: { agentName: agentName ?? "", type: type ?? "" }
|
|
1490
|
+
},
|
|
1491
|
+
error$1
|
|
1492
|
+
);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
964
1495
|
parseWorkflowRun(row) {
|
|
965
1496
|
let parsedSnapshot = row.snapshot;
|
|
966
1497
|
if (typeof parsedSnapshot === "string") {
|
|
@@ -1028,11 +1559,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
1028
1559
|
const results = await this.executeQuery({ sql, params });
|
|
1029
1560
|
const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
|
|
1030
1561
|
return { runs, total: total || runs.length };
|
|
1031
|
-
} catch (error) {
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1562
|
+
} catch (error$1) {
|
|
1563
|
+
throw new error.MastraError(
|
|
1564
|
+
{
|
|
1565
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
|
|
1566
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1567
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1568
|
+
text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1569
|
+
details: { workflowName: workflowName ?? "", resourceId: resourceId ?? "" }
|
|
1570
|
+
},
|
|
1571
|
+
error$1
|
|
1572
|
+
);
|
|
1036
1573
|
}
|
|
1037
1574
|
}
|
|
1038
1575
|
async getWorkflowRunById({
|
|
@@ -1056,11 +1593,17 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
1056
1593
|
const result = await this.executeQuery({ sql, params, first: true });
|
|
1057
1594
|
if (!result) return null;
|
|
1058
1595
|
return this.parseWorkflowRun(result);
|
|
1059
|
-
} catch (error) {
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1596
|
+
} catch (error$1) {
|
|
1597
|
+
throw new error.MastraError(
|
|
1598
|
+
{
|
|
1599
|
+
id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
|
|
1600
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1601
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1602
|
+
text: `Failed to retrieve workflow run by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
|
|
1603
|
+
details: { runId, workflowName: workflowName ?? "" }
|
|
1604
|
+
},
|
|
1605
|
+
error$1
|
|
1606
|
+
);
|
|
1064
1607
|
}
|
|
1065
1608
|
}
|
|
1066
1609
|
/**
|
|
@@ -1070,6 +1613,10 @@ var D1Store = class extends storage.MastraStorage {
|
|
|
1070
1613
|
async close() {
|
|
1071
1614
|
this.logger.debug("Closing D1 connection");
|
|
1072
1615
|
}
|
|
1616
|
+
async updateMessages(_args) {
|
|
1617
|
+
this.logger.error("updateMessages is not yet implemented in CloudflareD1Store");
|
|
1618
|
+
throw new Error("Method not implemented");
|
|
1619
|
+
}
|
|
1073
1620
|
};
|
|
1074
1621
|
|
|
1075
1622
|
exports.D1Store = D1Store;
|