@mastra/cloudflare-d1 0.0.0-support-d1-client-20250701191943 → 0.0.0-suspendRuntimeContextTypeFix-20250930142630

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var agent = require('@mastra/core/agent');
4
3
  var error = require('@mastra/core/error');
5
4
  var storage = require('@mastra/core/storage');
6
5
  var Cloudflare = require('cloudflare');
7
6
  var utils = require('@mastra/core/utils');
7
+ var agent = require('@mastra/core/agent');
8
+ var scores = require('@mastra/core/scores');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -241,402 +242,301 @@ function parseSelectIdentifier(column) {
241
242
  return column;
242
243
  }
243
244
 
244
- // src/storage/index.ts
245
+ // src/storage/domains/utils.ts
245
246
  function isArrayOfRecords(value) {
246
247
  return value && Array.isArray(value) && value.length > 0;
247
248
  }
248
- var D1Store = class extends storage.MastraStorage {
249
- client;
250
- binding;
251
- // D1Database binding
252
- tablePrefix;
253
- /**
254
- * Creates a new D1Store instance
255
- * @param config Configuration for D1 access (either REST API or Workers Binding API)
256
- */
257
- constructor(config) {
258
- try {
259
- super({ name: "D1" });
260
- if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
261
- throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
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");
267
- }
268
- this.binding = config.binding;
269
- this.logger.info("Using D1 Workers Binding API");
270
- } else if ("client" in config) {
271
- if (!config.client) {
272
- throw new Error("D1 client is required when using D1ClientConfig");
273
- }
274
- this.client = config.client;
275
- this.logger.info("Using D1 Client");
276
- } else {
277
- if (!config.accountId || !config.databaseId || !config.apiToken) {
278
- throw new Error("accountId, databaseId, and apiToken are required when using REST API");
279
- }
280
- const cfClient = new Cloudflare__default.default({
281
- apiToken: config.apiToken
282
- });
283
- this.client = {
284
- query: ({ sql, params }) => {
285
- return cfClient.d1.database.query(config.databaseId, {
286
- account_id: config.accountId,
287
- sql,
288
- params
289
- });
290
- }
291
- };
292
- this.logger.info("Using D1 REST API");
293
- }
294
- } catch (error$1) {
295
- throw new error.MastraError(
296
- {
297
- id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
298
- domain: error.ErrorDomain.STORAGE,
299
- category: error.ErrorCategory.SYSTEM,
300
- text: "Error initializing D1Store"
301
- },
302
- error$1
303
- );
304
- }
305
- }
306
- // Helper method to get the full table name with prefix
307
- getTableName(tableName) {
308
- return `${this.tablePrefix}${tableName}`;
309
- }
310
- formatSqlParams(params) {
311
- return params.map((p) => p === void 0 || p === null ? null : p);
312
- }
313
- async executeWorkersBindingQuery({
314
- sql,
315
- params = [],
316
- first = false
317
- }) {
318
- if (!this.binding) {
319
- throw new Error("Workers binding is not configured");
320
- }
321
- try {
322
- const statement = this.binding.prepare(sql);
323
- const formattedParams = this.formatSqlParams(params);
324
- let result;
325
- if (formattedParams.length > 0) {
326
- if (first) {
327
- result = await statement.bind(...formattedParams).first();
328
- if (!result) return null;
329
- return result;
330
- } else {
331
- result = await statement.bind(...formattedParams).all();
332
- const results = result.results || [];
333
- if (result.meta) {
334
- this.logger.debug("Query metadata", { meta: result.meta });
335
- }
336
- return results;
337
- }
338
- } else {
339
- if (first) {
340
- result = await statement.first();
341
- if (!result) return null;
342
- return result;
343
- } else {
344
- result = await statement.all();
345
- const results = result.results || [];
346
- if (result.meta) {
347
- this.logger.debug("Query metadata", { meta: result.meta });
348
- }
349
- return results;
350
- }
351
- }
352
- } catch (workerError) {
353
- this.logger.error("Workers Binding API error", {
354
- message: workerError instanceof Error ? workerError.message : String(workerError),
355
- sql
356
- });
357
- throw new Error(`D1 Workers API error: ${workerError.message}`);
358
- }
359
- }
360
- async executeRestQuery({
361
- sql,
362
- params = [],
363
- first = false
364
- }) {
365
- if (!this.client) {
366
- throw new Error("Missing required REST API configuration");
367
- }
368
- try {
369
- const response = await this.client.query({
370
- sql,
371
- params: this.formatSqlParams(params)
372
- });
373
- const result = response.result || [];
374
- const results = result.flatMap((r) => r.results || []);
375
- if (first) {
376
- const firstResult = isArrayOfRecords(results) && results.length > 0 ? results[0] : null;
377
- if (!firstResult) return null;
378
- return firstResult;
379
- }
380
- return results;
381
- } catch (restError) {
382
- this.logger.error("REST API error", {
383
- message: restError instanceof Error ? restError.message : String(restError),
384
- sql
385
- });
386
- throw new Error(`D1 REST API error: ${restError.message}`);
387
- }
249
+ function deserializeValue(value, type) {
250
+ if (value === null || value === void 0) return null;
251
+ if (type === "date" && typeof value === "string") {
252
+ return new Date(value);
388
253
  }
389
- /**
390
- * Execute a SQL query against the D1 database
391
- * @param options Query options including SQL, parameters, and whether to return only the first result
392
- * @returns Query results as an array or a single object if first=true
393
- */
394
- async executeQuery(options) {
395
- const { sql, params = [], first = false } = options;
254
+ if (type === "jsonb" && typeof value === "string") {
396
255
  try {
397
- this.logger.debug("Executing SQL query", { sql, params, first });
398
- if (this.binding) {
399
- return this.executeWorkersBindingQuery({ sql, params, first });
400
- } else if (this.client) {
401
- return this.executeRestQuery({ sql, params, first });
402
- } else {
403
- throw new Error("No valid D1 configuration provided");
404
- }
405
- } catch (error) {
406
- this.logger.error("Error executing SQL query", {
407
- message: error instanceof Error ? error.message : String(error),
408
- sql,
409
- params,
410
- first
411
- });
412
- throw new Error(`D1 query error: ${error.message}`);
256
+ return JSON.parse(value);
257
+ } catch {
258
+ return value;
413
259
  }
414
260
  }
415
- // Helper to get existing table columns
416
- async getTableColumns(tableName) {
261
+ if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
417
262
  try {
418
- const sql = `PRAGMA table_info(${tableName})`;
419
- const result = await this.executeQuery({ sql, params: [] });
420
- if (!result || !Array.isArray(result)) {
421
- return [];
422
- }
423
- return result.map((row) => ({
424
- name: row.name,
425
- type: row.type
426
- }));
427
- } catch (error) {
428
- this.logger.error(`Error getting table columns for ${tableName}:`, {
429
- message: error instanceof Error ? error.message : String(error)
430
- });
431
- return [];
263
+ return JSON.parse(value);
264
+ } catch {
265
+ return value;
432
266
  }
433
267
  }
434
- // Helper to serialize objects to JSON strings
435
- serializeValue(value) {
436
- if (value === null || value === void 0) return null;
437
- if (value instanceof Date) {
438
- return this.serializeDate(value);
439
- }
440
- if (typeof value === "object") {
441
- return JSON.stringify(value);
442
- }
443
- return value;
268
+ return value;
269
+ }
270
+
271
+ // src/storage/domains/legacy-evals/index.ts
272
+ var LegacyEvalsStorageD1 = class extends storage.LegacyEvalsStorage {
273
+ operations;
274
+ constructor({ operations }) {
275
+ super();
276
+ this.operations = operations;
444
277
  }
445
- // Helper to deserialize JSON strings to objects
446
- deserializeValue(value, type) {
447
- if (value === null || value === void 0) return null;
448
- if (type === "date" && typeof value === "string") {
449
- return new Date(value);
278
+ async getEvals(options) {
279
+ const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
280
+ const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
281
+ const conditions = [];
282
+ const queryParams = [];
283
+ if (agentName) {
284
+ conditions.push(`agent_name = ?`);
285
+ queryParams.push(agentName);
450
286
  }
451
- if (type === "jsonb" && typeof value === "string") {
452
- try {
453
- return JSON.parse(value);
454
- } catch {
455
- return value;
456
- }
287
+ if (type === "test") {
288
+ conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
289
+ } else if (type === "live") {
290
+ conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
457
291
  }
458
- if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
459
- try {
460
- return JSON.parse(value);
461
- } catch {
462
- return value;
463
- }
292
+ if (dateRange?.start) {
293
+ conditions.push(`created_at >= ?`);
294
+ queryParams.push(storage.serializeDate(dateRange.start));
464
295
  }
465
- return value;
466
- }
467
- getSqlType(type) {
468
- switch (type) {
469
- case "bigint":
470
- return "INTEGER";
471
- // SQLite uses INTEGER for all integer sizes
472
- case "jsonb":
473
- return "TEXT";
474
- // Store JSON as TEXT in SQLite
475
- default:
476
- return super.getSqlType(type);
296
+ if (dateRange?.end) {
297
+ conditions.push(`created_at <= ?`);
298
+ queryParams.push(storage.serializeDate(dateRange.end));
477
299
  }
478
- }
479
- async createTable({
480
- tableName,
481
- schema
482
- }) {
483
- const fullTableName = this.getTableName(tableName);
484
- const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
485
- const type = this.getSqlType(colDef.type);
486
- const nullable = colDef.nullable === false ? "NOT NULL" : "";
487
- const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
488
- return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
489
- });
490
- const tableConstraints = [];
491
- if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
492
- tableConstraints.push("UNIQUE (workflow_name, run_id)");
300
+ const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
301
+ if (conditions.length > 0) {
302
+ countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
493
303
  }
304
+ const { sql: countSql, params: countParams } = countQueryBuilder.build();
494
305
  try {
495
- const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
496
- const { sql, params } = query.build();
497
- await this.executeQuery({ sql, params });
498
- this.logger.debug(`Created table ${fullTableName}`);
499
- } catch (error$1) {
500
- this.logger.error(`Error creating table ${fullTableName}:`, {
501
- message: error$1 instanceof Error ? error$1.message : String(error$1)
306
+ const countResult = await this.operations.executeQuery({
307
+ sql: countSql,
308
+ params: countParams,
309
+ first: true
310
+ });
311
+ const total = Number(countResult?.count || 0);
312
+ const currentOffset = page * perPage;
313
+ if (total === 0) {
314
+ return {
315
+ evals: [],
316
+ total: 0,
317
+ page,
318
+ perPage,
319
+ hasMore: false
320
+ };
321
+ }
322
+ const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
323
+ if (conditions.length > 0) {
324
+ dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
325
+ }
326
+ dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
327
+ const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
328
+ const rows = await this.operations.executeQuery({
329
+ sql: dataSql,
330
+ params: dataParams
331
+ });
332
+ const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
333
+ const result = deserializeValue(row.result);
334
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
335
+ if (!result || typeof result !== "object" || !("score" in result)) {
336
+ throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
337
+ }
338
+ return {
339
+ input: row.input,
340
+ output: row.output,
341
+ result,
342
+ agentName: row.agent_name,
343
+ metricName: row.metric_name,
344
+ instructions: row.instructions,
345
+ testInfo,
346
+ globalRunId: row.global_run_id,
347
+ runId: row.run_id,
348
+ createdAt: row.created_at
349
+ };
502
350
  });
351
+ const hasMore = currentOffset + evals.length < total;
352
+ return {
353
+ evals,
354
+ total,
355
+ page,
356
+ perPage,
357
+ hasMore
358
+ };
359
+ } catch (error$1) {
503
360
  throw new error.MastraError(
504
361
  {
505
- id: "CLOUDFLARE_D1_STORAGE_CREATE_TABLE_ERROR",
362
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
506
363
  domain: error.ErrorDomain.STORAGE,
507
364
  category: error.ErrorCategory.THIRD_PARTY,
508
- text: `Failed to create table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
509
- details: { tableName }
365
+ text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
366
+ details: { agentName: agentName ?? "", type: type ?? "" }
510
367
  },
511
368
  error$1
512
369
  );
513
370
  }
514
371
  }
515
372
  /**
516
- * Alters table schema to add columns if they don't exist
517
- * @param tableName Name of the table
518
- * @param schema Schema of the table
519
- * @param ifNotExists Array of column names to add if they don't exist
373
+ * @deprecated use getEvals instead
520
374
  */
521
- async alterTable({
522
- tableName,
523
- schema,
524
- ifNotExists
525
- }) {
526
- const fullTableName = this.getTableName(tableName);
375
+ async getEvalsByAgentName(agentName, type) {
376
+ const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
527
377
  try {
528
- const existingColumns = await this.getTableColumns(fullTableName);
529
- const existingColumnNames = new Set(existingColumns.map((col) => col.name.toLowerCase()));
530
- for (const columnName of ifNotExists) {
531
- if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
532
- const columnDef = schema[columnName];
533
- const sqlType = this.getSqlType(columnDef.type);
534
- const nullable = columnDef.nullable === false ? "NOT NULL" : "";
535
- const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
536
- const alterSql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${nullable} ${defaultValue}`.trim();
537
- await this.executeQuery({ sql: alterSql, params: [] });
538
- this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
539
- }
378
+ let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
379
+ if (type === "test") {
380
+ query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
381
+ } else if (type === "live") {
382
+ query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
540
383
  }
384
+ query.orderBy("created_at", "DESC");
385
+ const { sql, params } = query.build();
386
+ const results = await this.operations.executeQuery({ sql, params });
387
+ return isArrayOfRecords(results) ? results.map((row) => {
388
+ const result = deserializeValue(row.result);
389
+ const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
390
+ return {
391
+ input: row.input || "",
392
+ output: row.output || "",
393
+ result,
394
+ agentName: row.agent_name || "",
395
+ metricName: row.metric_name || "",
396
+ instructions: row.instructions || "",
397
+ runId: row.run_id || "",
398
+ globalRunId: row.global_run_id || "",
399
+ createdAt: row.created_at || "",
400
+ testInfo
401
+ };
402
+ }) : [];
541
403
  } catch (error$1) {
542
- throw new error.MastraError(
404
+ const mastraError = new error.MastraError(
543
405
  {
544
- id: "CLOUDFLARE_D1_STORAGE_ALTER_TABLE_ERROR",
406
+ id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
545
407
  domain: error.ErrorDomain.STORAGE,
546
408
  category: error.ErrorCategory.THIRD_PARTY,
547
- text: `Failed to alter table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
548
- details: { tableName }
409
+ text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
410
+ details: { agentName }
549
411
  },
550
412
  error$1
551
413
  );
414
+ this.logger?.error(mastraError.toString());
415
+ this.logger?.trackException(mastraError);
416
+ return [];
552
417
  }
553
418
  }
554
- async clearTable({ tableName }) {
555
- const fullTableName = this.getTableName(tableName);
419
+ };
420
+ var MemoryStorageD1 = class extends storage.MemoryStorage {
421
+ operations;
422
+ constructor({ operations }) {
423
+ super();
424
+ this.operations = operations;
425
+ }
426
+ async getResourceById({ resourceId }) {
427
+ const resource = await this.operations.load({
428
+ tableName: storage.TABLE_RESOURCES,
429
+ keys: { id: resourceId }
430
+ });
431
+ if (!resource) return null;
556
432
  try {
557
- const query = createSqlBuilder().delete(fullTableName);
558
- const { sql, params } = query.build();
559
- await this.executeQuery({ sql, params });
560
- this.logger.debug(`Cleared table ${fullTableName}`);
433
+ return {
434
+ ...resource,
435
+ createdAt: storage.ensureDate(resource.createdAt),
436
+ updatedAt: storage.ensureDate(resource.updatedAt),
437
+ metadata: typeof resource.metadata === "string" ? JSON.parse(resource.metadata || "{}") : resource.metadata
438
+ };
561
439
  } catch (error$1) {
562
- throw new error.MastraError(
440
+ const mastraError = new error.MastraError(
563
441
  {
564
- id: "CLOUDFLARE_D1_STORAGE_CLEAR_TABLE_ERROR",
442
+ id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
565
443
  domain: error.ErrorDomain.STORAGE,
566
444
  category: error.ErrorCategory.THIRD_PARTY,
567
- text: `Failed to clear table ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
568
- details: { tableName }
445
+ text: `Error processing resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
446
+ details: { resourceId }
569
447
  },
570
448
  error$1
571
449
  );
450
+ this.logger?.error(mastraError.toString());
451
+ this.logger?.trackException(mastraError);
452
+ return null;
572
453
  }
573
454
  }
574
- async processRecord(record) {
575
- const processedRecord = {};
576
- for (const [key, value] of Object.entries(record)) {
577
- processedRecord[key] = this.serializeValue(value);
578
- }
579
- return processedRecord;
580
- }
581
- async insert({ tableName, record }) {
582
- const fullTableName = this.getTableName(tableName);
583
- const processedRecord = await this.processRecord(record);
455
+ async saveResource({ resource }) {
456
+ const fullTableName = this.operations.getTableName(storage.TABLE_RESOURCES);
457
+ const resourceToSave = {
458
+ id: resource.id,
459
+ workingMemory: resource.workingMemory,
460
+ metadata: resource.metadata ? JSON.stringify(resource.metadata) : null,
461
+ createdAt: resource.createdAt,
462
+ updatedAt: resource.updatedAt
463
+ };
464
+ const processedRecord = await this.operations.processRecord(resourceToSave);
584
465
  const columns = Object.keys(processedRecord);
585
466
  const values = Object.values(processedRecord);
586
- const query = createSqlBuilder().insert(fullTableName, columns, values);
467
+ const updateMap = {
468
+ workingMemory: "excluded.workingMemory",
469
+ metadata: "excluded.metadata",
470
+ createdAt: "excluded.createdAt",
471
+ updatedAt: "excluded.updatedAt"
472
+ };
473
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
587
474
  const { sql, params } = query.build();
588
475
  try {
589
- await this.executeQuery({ sql, params });
476
+ await this.operations.executeQuery({ sql, params });
477
+ return resource;
590
478
  } catch (error$1) {
591
479
  throw new error.MastraError(
592
480
  {
593
- id: "CLOUDFLARE_D1_STORAGE_INSERT_ERROR",
481
+ id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
594
482
  domain: error.ErrorDomain.STORAGE,
595
483
  category: error.ErrorCategory.THIRD_PARTY,
596
- text: `Failed to insert into ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
597
- details: { tableName }
484
+ text: `Failed to save resource to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
485
+ details: { resourceId: resource.id }
598
486
  },
599
487
  error$1
600
488
  );
601
489
  }
602
490
  }
603
- async load({ tableName, keys }) {
604
- const fullTableName = this.getTableName(tableName);
605
- const query = createSqlBuilder().select("*").from(fullTableName);
606
- let firstKey = true;
607
- for (const [key, value] of Object.entries(keys)) {
608
- if (firstKey) {
609
- query.where(`${key} = ?`, value);
610
- firstKey = false;
611
- } else {
612
- query.andWhere(`${key} = ?`, value);
613
- }
491
+ async updateResource({
492
+ resourceId,
493
+ workingMemory,
494
+ metadata
495
+ }) {
496
+ const existingResource = await this.getResourceById({ resourceId });
497
+ if (!existingResource) {
498
+ const newResource = {
499
+ id: resourceId,
500
+ workingMemory,
501
+ metadata: metadata || {},
502
+ createdAt: /* @__PURE__ */ new Date(),
503
+ updatedAt: /* @__PURE__ */ new Date()
504
+ };
505
+ return this.saveResource({ resource: newResource });
614
506
  }
615
- query.limit(1);
507
+ const updatedAt = /* @__PURE__ */ new Date();
508
+ const updatedResource = {
509
+ ...existingResource,
510
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
511
+ metadata: {
512
+ ...existingResource.metadata,
513
+ ...metadata
514
+ },
515
+ updatedAt
516
+ };
517
+ const fullTableName = this.operations.getTableName(storage.TABLE_RESOURCES);
518
+ const columns = ["workingMemory", "metadata", "updatedAt"];
519
+ const values = [updatedResource.workingMemory, JSON.stringify(updatedResource.metadata), updatedAt.toISOString()];
520
+ const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", resourceId);
616
521
  const { sql, params } = query.build();
617
522
  try {
618
- const result = await this.executeQuery({ sql, params, first: true });
619
- if (!result) return null;
620
- const processedResult = {};
621
- for (const [key, value] of Object.entries(result)) {
622
- processedResult[key] = this.deserializeValue(value);
623
- }
624
- return processedResult;
523
+ await this.operations.executeQuery({ sql, params });
524
+ return updatedResource;
625
525
  } catch (error$1) {
626
526
  throw new error.MastraError(
627
527
  {
628
- id: "CLOUDFLARE_D1_STORAGE_LOAD_ERROR",
528
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
629
529
  domain: error.ErrorDomain.STORAGE,
630
530
  category: error.ErrorCategory.THIRD_PARTY,
631
- text: `Failed to load from ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
632
- details: { tableName }
531
+ text: `Failed to update resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
532
+ details: { resourceId }
633
533
  },
634
534
  error$1
635
535
  );
636
536
  }
637
537
  }
638
538
  async getThreadById({ threadId }) {
639
- const thread = await this.load({
539
+ const thread = await this.operations.load({
640
540
  tableName: storage.TABLE_THREADS,
641
541
  keys: { id: threadId }
642
542
  });
@@ -644,8 +544,8 @@ var D1Store = class extends storage.MastraStorage {
644
544
  try {
645
545
  return {
646
546
  ...thread,
647
- createdAt: this.ensureDate(thread.createdAt),
648
- updatedAt: this.ensureDate(thread.updatedAt),
547
+ createdAt: storage.ensureDate(thread.createdAt),
548
+ updatedAt: storage.ensureDate(thread.updatedAt),
649
549
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
650
550
  };
651
551
  } catch (error$1) {
@@ -668,15 +568,15 @@ var D1Store = class extends storage.MastraStorage {
668
568
  * @deprecated use getThreadsByResourceIdPaginated instead
669
569
  */
670
570
  async getThreadsByResourceId({ resourceId }) {
671
- const fullTableName = this.getTableName(storage.TABLE_THREADS);
571
+ const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
672
572
  try {
673
573
  const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
674
574
  const { sql, params } = query.build();
675
- const results = await this.executeQuery({ sql, params });
575
+ const results = await this.operations.executeQuery({ sql, params });
676
576
  return (isArrayOfRecords(results) ? results : []).map((thread) => ({
677
577
  ...thread,
678
- createdAt: this.ensureDate(thread.createdAt),
679
- updatedAt: this.ensureDate(thread.updatedAt),
578
+ createdAt: storage.ensureDate(thread.createdAt),
579
+ updatedAt: storage.ensureDate(thread.updatedAt),
680
580
  metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
681
581
  }));
682
582
  } catch (error$1) {
@@ -697,19 +597,19 @@ var D1Store = class extends storage.MastraStorage {
697
597
  }
698
598
  async getThreadsByResourceIdPaginated(args) {
699
599
  const { resourceId, page, perPage } = args;
700
- const fullTableName = this.getTableName(storage.TABLE_THREADS);
600
+ const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
701
601
  const mapRowToStorageThreadType = (row) => ({
702
602
  ...row,
703
- createdAt: this.ensureDate(row.createdAt),
704
- updatedAt: this.ensureDate(row.updatedAt),
603
+ createdAt: storage.ensureDate(row.createdAt),
604
+ updatedAt: storage.ensureDate(row.updatedAt),
705
605
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata || "{}") : row.metadata || {}
706
606
  });
707
607
  try {
708
608
  const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
709
- const countResult = await this.executeQuery(countQuery.build());
609
+ const countResult = await this.operations.executeQuery(countQuery.build());
710
610
  const total = Number(countResult?.[0]?.count ?? 0);
711
611
  const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
712
- const results = await this.executeQuery(selectQuery.build());
612
+ const results = await this.operations.executeQuery(selectQuery.build());
713
613
  const threads = results.map(mapRowToStorageThreadType);
714
614
  return {
715
615
  threads,
@@ -741,16 +641,16 @@ var D1Store = class extends storage.MastraStorage {
741
641
  }
742
642
  }
743
643
  async saveThread({ thread }) {
744
- const fullTableName = this.getTableName(storage.TABLE_THREADS);
644
+ const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
745
645
  const threadToSave = {
746
646
  id: thread.id,
747
647
  resourceId: thread.resourceId,
748
648
  title: thread.title,
749
649
  metadata: thread.metadata ? JSON.stringify(thread.metadata) : null,
750
- createdAt: thread.createdAt,
751
- updatedAt: thread.updatedAt
650
+ createdAt: thread.createdAt.toISOString(),
651
+ updatedAt: thread.updatedAt.toISOString()
752
652
  };
753
- const processedRecord = await this.processRecord(threadToSave);
653
+ const processedRecord = await this.operations.processRecord(threadToSave);
754
654
  const columns = Object.keys(processedRecord);
755
655
  const values = Object.values(processedRecord);
756
656
  const updateMap = {
@@ -763,7 +663,7 @@ var D1Store = class extends storage.MastraStorage {
763
663
  const query = createSqlBuilder().insert(fullTableName, columns, values, ["id"], updateMap);
764
664
  const { sql, params } = query.build();
765
665
  try {
766
- await this.executeQuery({ sql, params });
666
+ await this.operations.executeQuery({ sql, params });
767
667
  return thread;
768
668
  } catch (error$1) {
769
669
  throw new error.MastraError(
@@ -788,16 +688,17 @@ var D1Store = class extends storage.MastraStorage {
788
688
  if (!thread) {
789
689
  throw new Error(`Thread ${id} not found`);
790
690
  }
791
- const fullTableName = this.getTableName(storage.TABLE_THREADS);
691
+ const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
792
692
  const mergedMetadata = {
793
693
  ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
794
694
  ...metadata
795
695
  };
696
+ const updatedAt = /* @__PURE__ */ new Date();
796
697
  const columns = ["title", "metadata", "updatedAt"];
797
- const values = [title, JSON.stringify(mergedMetadata), (/* @__PURE__ */ new Date()).toISOString()];
698
+ const values = [title, JSON.stringify(mergedMetadata), updatedAt.toISOString()];
798
699
  const query = createSqlBuilder().update(fullTableName, columns, values).where("id = ?", id);
799
700
  const { sql, params } = query.build();
800
- await this.executeQuery({ sql, params });
701
+ await this.operations.executeQuery({ sql, params });
801
702
  return {
802
703
  ...thread,
803
704
  title,
@@ -805,7 +706,7 @@ var D1Store = class extends storage.MastraStorage {
805
706
  ...typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
806
707
  ...metadata
807
708
  },
808
- updatedAt: /* @__PURE__ */ new Date()
709
+ updatedAt
809
710
  };
810
711
  } catch (error$1) {
811
712
  throw new error.MastraError(
@@ -821,15 +722,15 @@ var D1Store = class extends storage.MastraStorage {
821
722
  }
822
723
  }
823
724
  async deleteThread({ threadId }) {
824
- const fullTableName = this.getTableName(storage.TABLE_THREADS);
725
+ const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
825
726
  try {
826
727
  const deleteThreadQuery = createSqlBuilder().delete(fullTableName).where("id = ?", threadId);
827
728
  const { sql: threadSql, params: threadParams } = deleteThreadQuery.build();
828
- await this.executeQuery({ sql: threadSql, params: threadParams });
829
- const messagesTableName = this.getTableName(storage.TABLE_MESSAGES);
729
+ await this.operations.executeQuery({ sql: threadSql, params: threadParams });
730
+ const messagesTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
830
731
  const deleteMessagesQuery = createSqlBuilder().delete(messagesTableName).where("thread_id = ?", threadId);
831
732
  const { sql: messagesSql, params: messagesParams } = deleteMessagesQuery.build();
832
- await this.executeQuery({ sql: messagesSql, params: messagesParams });
733
+ await this.operations.executeQuery({ sql: messagesSql, params: messagesParams });
833
734
  } catch (error$1) {
834
735
  throw new error.MastraError(
835
736
  {
@@ -860,6 +761,9 @@ var D1Store = class extends storage.MastraStorage {
860
761
  if (!message.role) {
861
762
  throw new Error(`Message at index ${i} missing role`);
862
763
  }
764
+ if (!message.resourceId) {
765
+ throw new Error(`Message at index ${i} missing resourceId`);
766
+ }
863
767
  const thread = await this.getThreadById({ threadId: message.threadId });
864
768
  if (!thread) {
865
769
  throw new Error(`Thread ${message.threadId} not found`);
@@ -878,13 +782,13 @@ var D1Store = class extends storage.MastraStorage {
878
782
  };
879
783
  });
880
784
  await Promise.all([
881
- this.batchUpsert({
785
+ this.operations.batchUpsert({
882
786
  tableName: storage.TABLE_MESSAGES,
883
787
  records: messagesToInsert
884
788
  }),
885
789
  // Update thread's updatedAt timestamp
886
- this.executeQuery({
887
- sql: `UPDATE ${this.getTableName(storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
790
+ this.operations.executeQuery({
791
+ sql: `UPDATE ${this.operations.getTableName(storage.TABLE_THREADS)} SET updatedAt = ? WHERE id = ?`,
888
792
  params: [now.toISOString(), threadId]
889
793
  })
890
794
  ]);
@@ -905,64 +809,78 @@ var D1Store = class extends storage.MastraStorage {
905
809
  }
906
810
  }
907
811
  async _getIncludedMessages(threadId, selectBy) {
812
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
908
813
  const include = selectBy?.include;
909
814
  if (!include) return null;
910
- const prevMax = Math.max(...include.map((i) => i.withPreviousMessages || 0));
911
- const nextMax = Math.max(...include.map((i) => i.withNextMessages || 0));
912
- const includeIds = include.map((i) => i.id);
913
- const sql = `
914
- WITH ordered_messages AS (
915
- SELECT
916
- *,
917
- ROW_NUMBER() OVER (ORDER BY createdAt DESC) AS row_num
918
- FROM ${this.getTableName(storage.TABLE_MESSAGES)}
919
- WHERE thread_id = ?
920
- )
921
- SELECT
922
- m.id,
923
- m.content,
924
- m.role,
925
- m.type,
926
- m.createdAt,
927
- m.thread_id AS threadId
928
- FROM ordered_messages m
929
- WHERE m.id IN (${includeIds.map(() => "?").join(",")})
930
- OR EXISTS (
931
- SELECT 1 FROM ordered_messages target
932
- WHERE target.id IN (${includeIds.map(() => "?").join(",")})
933
- AND (
934
- (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
935
- OR
936
- (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
937
- )
938
- )
939
- ORDER BY m.createdAt DESC
940
- `;
941
- const params = [
942
- threadId,
943
- ...includeIds,
944
- // for m.id IN (...)
945
- ...includeIds,
946
- // for target.id IN (...)
947
- prevMax,
948
- nextMax
949
- ];
950
- const messages = await this.executeQuery({ sql, params });
951
- return messages;
815
+ const unionQueries = [];
816
+ const params = [];
817
+ let paramIdx = 1;
818
+ for (const inc of include) {
819
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
820
+ const searchId = inc.threadId || threadId;
821
+ unionQueries.push(`
822
+ SELECT * FROM (
823
+ WITH ordered_messages AS (
824
+ SELECT
825
+ *,
826
+ ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
827
+ FROM ${this.operations.getTableName(storage.TABLE_MESSAGES)}
828
+ WHERE thread_id = ?
829
+ )
830
+ SELECT
831
+ m.id,
832
+ m.content,
833
+ m.role,
834
+ m.type,
835
+ m.createdAt,
836
+ m.thread_id AS threadId,
837
+ m.resourceId
838
+ FROM ordered_messages m
839
+ WHERE m.id = ?
840
+ OR EXISTS (
841
+ SELECT 1 FROM ordered_messages target
842
+ WHERE target.id = ?
843
+ AND (
844
+ (m.row_num <= target.row_num + ? AND m.row_num > target.row_num)
845
+ OR
846
+ (m.row_num >= target.row_num - ? AND m.row_num < target.row_num)
847
+ )
848
+ )
849
+ ) AS query_${paramIdx}
850
+ `);
851
+ params.push(searchId, id, id, withNextMessages, withPreviousMessages);
852
+ paramIdx++;
853
+ }
854
+ const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
855
+ const messages = await this.operations.executeQuery({ sql: finalQuery, params });
856
+ if (!Array.isArray(messages)) {
857
+ return [];
858
+ }
859
+ const processedMessages = messages.map((message) => {
860
+ const processedMsg = {};
861
+ for (const [key, value] of Object.entries(message)) {
862
+ if (key === `type` && value === `v2`) continue;
863
+ processedMsg[key] = deserializeValue(value);
864
+ }
865
+ return processedMsg;
866
+ });
867
+ return processedMessages;
952
868
  }
953
869
  async getMessages({
954
870
  threadId,
871
+ resourceId,
955
872
  selectBy,
956
873
  format
957
874
  }) {
958
- const fullTableName = this.getTableName(storage.TABLE_MESSAGES);
959
- const limit = this.resolveMessageLimit({
960
- last: selectBy?.last,
961
- defaultLimit: 40
962
- });
963
- const include = selectBy?.include || [];
964
- const messages = [];
965
875
  try {
876
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
877
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
878
+ const limit = storage.resolveMessageLimit({
879
+ last: selectBy?.last,
880
+ defaultLimit: 40
881
+ });
882
+ const include = selectBy?.include || [];
883
+ const messages = [];
966
884
  if (include.length) {
967
885
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
968
886
  if (Array.isArray(includeResult)) messages.push(...includeResult);
@@ -974,7 +892,7 @@ var D1Store = class extends storage.MastraStorage {
974
892
  }
975
893
  query.orderBy("createdAt", "DESC").limit(limit);
976
894
  const { sql, params } = query.build();
977
- const result = await this.executeQuery({ sql, params });
895
+ const result = await this.operations.executeQuery({ sql, params });
978
896
  if (Array.isArray(result)) messages.push(...result);
979
897
  messages.sort((a, b) => {
980
898
  const aRecord = a;
@@ -987,7 +905,7 @@ var D1Store = class extends storage.MastraStorage {
987
905
  const processedMsg = {};
988
906
  for (const [key, value] of Object.entries(message)) {
989
907
  if (key === `type` && value === `v2`) continue;
990
- processedMsg[key] = this.deserializeValue(value);
908
+ processedMsg[key] = deserializeValue(value);
991
909
  }
992
910
  return processedMsg;
993
911
  });
@@ -1002,7 +920,48 @@ var D1Store = class extends storage.MastraStorage {
1002
920
  domain: error.ErrorDomain.STORAGE,
1003
921
  category: error.ErrorCategory.THIRD_PARTY,
1004
922
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1005
- details: { threadId }
923
+ details: { threadId, resourceId: resourceId ?? "" }
924
+ },
925
+ error$1
926
+ );
927
+ this.logger?.error(mastraError.toString());
928
+ this.logger?.trackException(mastraError);
929
+ throw mastraError;
930
+ }
931
+ }
932
+ async getMessagesById({
933
+ messageIds,
934
+ format
935
+ }) {
936
+ if (messageIds.length === 0) return [];
937
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
+ const messages = [];
939
+ try {
940
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
941
+ query.orderBy("createdAt", "DESC");
942
+ const { sql, params } = query.build();
943
+ const result = await this.operations.executeQuery({ sql, params });
944
+ if (Array.isArray(result)) messages.push(...result);
945
+ const processedMessages = messages.map((message) => {
946
+ const processedMsg = {};
947
+ for (const [key, value] of Object.entries(message)) {
948
+ if (key === `type` && value === `v2`) continue;
949
+ processedMsg[key] = deserializeValue(value);
950
+ }
951
+ return processedMsg;
952
+ });
953
+ this.logger.debug(`Retrieved ${messages.length} messages`);
954
+ const list = new agent.MessageList().add(processedMessages, "memory");
955
+ if (format === `v1`) return list.get.all.v1();
956
+ return list.get.all.v2();
957
+ } catch (error$1) {
958
+ const mastraError = new error.MastraError(
959
+ {
960
+ id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
961
+ domain: error.ErrorDomain.STORAGE,
962
+ category: error.ErrorCategory.THIRD_PARTY,
963
+ text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
964
+ details: { messageIds: JSON.stringify(messageIds) }
1006
965
  },
1007
966
  error$1
1008
967
  );
@@ -1013,44 +972,97 @@ var D1Store = class extends storage.MastraStorage {
1013
972
  }
1014
973
  async getMessagesPaginated({
1015
974
  threadId,
975
+ resourceId,
1016
976
  selectBy,
1017
977
  format
1018
978
  }) {
1019
- const { dateRange, page = 0, perPage = 40 } = selectBy?.pagination || {};
979
+ const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
1020
980
  const { start: fromDate, end: toDate } = dateRange || {};
1021
- const fullTableName = this.getTableName(storage.TABLE_MESSAGES);
981
+ const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
982
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
1022
983
  const messages = [];
1023
984
  try {
985
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1024
986
  if (selectBy?.include?.length) {
1025
987
  const includeResult = await this._getIncludedMessages(threadId, selectBy);
1026
988
  if (Array.isArray(includeResult)) messages.push(...includeResult);
1027
989
  }
1028
990
  const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
1029
991
  if (fromDate) {
1030
- countQuery.andWhere("createdAt >= ?", this.serializeDate(fromDate));
992
+ countQuery.andWhere("createdAt >= ?", storage.serializeDate(fromDate));
1031
993
  }
1032
994
  if (toDate) {
1033
- countQuery.andWhere("createdAt <= ?", this.serializeDate(toDate));
995
+ countQuery.andWhere("createdAt <= ?", storage.serializeDate(toDate));
1034
996
  }
1035
- const countResult = await this.executeQuery(countQuery.build());
997
+ const countResult = await this.operations.executeQuery(countQuery.build());
1036
998
  const total = Number(countResult[0]?.count ?? 0);
1037
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
999
+ if (total === 0 && messages.length === 0) {
1000
+ return {
1001
+ messages: [],
1002
+ total: 0,
1003
+ page,
1004
+ perPage,
1005
+ hasMore: false
1006
+ };
1007
+ }
1008
+ const excludeIds = messages.map((m) => m.id);
1009
+ const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
1010
+ let query;
1011
+ let queryParams = [threadId];
1038
1012
  if (fromDate) {
1039
- query.andWhere("createdAt >= ?", this.serializeDate(fromDate));
1013
+ queryParams.push(storage.serializeDate(fromDate));
1040
1014
  }
1041
1015
  if (toDate) {
1042
- query.andWhere("createdAt <= ?", this.serializeDate(toDate));
1016
+ queryParams.push(storage.serializeDate(toDate));
1017
+ }
1018
+ if (excludeIds.length > 0) {
1019
+ queryParams.push(...excludeIds);
1020
+ }
1021
+ if (selectBy?.last && selectBy.last > 0) {
1022
+ query = `
1023
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1024
+ FROM ${fullTableName}
1025
+ WHERE thread_id = ?
1026
+ ${fromDate ? "AND createdAt >= ?" : ""}
1027
+ ${toDate ? "AND createdAt <= ?" : ""}
1028
+ ${excludeCondition}
1029
+ ORDER BY createdAt DESC
1030
+ LIMIT ?
1031
+ `;
1032
+ queryParams.push(selectBy.last);
1033
+ } else {
1034
+ query = `
1035
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1036
+ FROM ${fullTableName}
1037
+ WHERE thread_id = ?
1038
+ ${fromDate ? "AND createdAt >= ?" : ""}
1039
+ ${toDate ? "AND createdAt <= ?" : ""}
1040
+ ${excludeCondition}
1041
+ ORDER BY createdAt DESC
1042
+ LIMIT ? OFFSET ?
1043
+ `;
1044
+ queryParams.push(perPage, page * perPage);
1043
1045
  }
1044
- query.orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
1045
- const results = await this.executeQuery(query.build());
1046
- const list = new agent.MessageList().add(results, "memory");
1046
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
1047
+ const processedMessages = results.map((message) => {
1048
+ const processedMsg = {};
1049
+ for (const [key, value] of Object.entries(message)) {
1050
+ if (key === `type` && value === `v2`) continue;
1051
+ processedMsg[key] = deserializeValue(value);
1052
+ }
1053
+ return processedMsg;
1054
+ });
1055
+ if (selectBy?.last) {
1056
+ processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1057
+ }
1058
+ const list = new agent.MessageList().add(processedMessages, "memory");
1047
1059
  messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
1048
1060
  return {
1049
1061
  messages,
1050
1062
  total,
1051
1063
  page,
1052
1064
  perPage,
1053
- hasMore: page * perPage + messages.length < total
1065
+ hasMore: selectBy?.last ? false : page * perPage + messages.length < total
1054
1066
  };
1055
1067
  } catch (error$1) {
1056
1068
  const mastraError = new error.MastraError(
@@ -1059,7 +1071,7 @@ var D1Store = class extends storage.MastraStorage {
1059
1071
  domain: error.ErrorDomain.STORAGE,
1060
1072
  category: error.ErrorCategory.THIRD_PARTY,
1061
1073
  text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1062
- details: { threadId }
1074
+ details: { threadId, resourceId: resourceId ?? "" }
1063
1075
  },
1064
1076
  error$1
1065
1077
  );
@@ -1074,132 +1086,446 @@ var D1Store = class extends storage.MastraStorage {
1074
1086
  };
1075
1087
  }
1076
1088
  }
1077
- async persistWorkflowSnapshot({
1078
- workflowName,
1079
- runId,
1080
- snapshot
1081
- }) {
1082
- const fullTableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1083
- const now = (/* @__PURE__ */ new Date()).toISOString();
1084
- const currentSnapshot = await this.load({
1085
- tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1086
- keys: { workflow_name: workflowName, run_id: runId }
1087
- });
1088
- const persisting = currentSnapshot ? {
1089
- ...currentSnapshot,
1090
- snapshot: JSON.stringify(snapshot),
1091
- updatedAt: now
1092
- } : {
1093
- workflow_name: workflowName,
1094
- run_id: runId,
1095
- snapshot,
1096
- createdAt: now,
1097
- updatedAt: now
1098
- };
1099
- const processedRecord = await this.processRecord(persisting);
1100
- const columns = Object.keys(processedRecord);
1101
- const values = Object.values(processedRecord);
1102
- const updateMap = {
1103
- snapshot: "excluded.snapshot",
1104
- updatedAt: "excluded.updatedAt"
1105
- };
1106
- this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
1107
- const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
1108
- const { sql, params } = query.build();
1089
+ async updateMessages(args) {
1090
+ const { messages } = args;
1091
+ this.logger.debug("Updating messages", { count: messages.length });
1092
+ if (!messages.length) {
1093
+ return [];
1094
+ }
1095
+ const messageIds = messages.map((m) => m.id);
1096
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
1097
+ const threadsTableName = this.operations.getTableName(storage.TABLE_THREADS);
1109
1098
  try {
1110
- await this.executeQuery({ sql, params });
1099
+ const placeholders = messageIds.map(() => "?").join(",");
1100
+ const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${placeholders})`;
1101
+ const existingMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1102
+ if (existingMessages.length === 0) {
1103
+ return [];
1104
+ }
1105
+ const parsedExistingMessages = existingMessages.map((msg) => {
1106
+ if (typeof msg.content === "string") {
1107
+ try {
1108
+ msg.content = JSON.parse(msg.content);
1109
+ } catch {
1110
+ }
1111
+ }
1112
+ return msg;
1113
+ });
1114
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
1115
+ const updateQueries = [];
1116
+ for (const existingMessage of parsedExistingMessages) {
1117
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
1118
+ if (!updatePayload) continue;
1119
+ const { id, ...fieldsToUpdate } = updatePayload;
1120
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
1121
+ threadIdsToUpdate.add(existingMessage.threadId);
1122
+ if ("threadId" in updatePayload && updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
1123
+ threadIdsToUpdate.add(updatePayload.threadId);
1124
+ }
1125
+ const setClauses = [];
1126
+ const values = [];
1127
+ const updatableFields = { ...fieldsToUpdate };
1128
+ if (updatableFields.content) {
1129
+ const existingContent = existingMessage.content || {};
1130
+ const newContent = {
1131
+ ...existingContent,
1132
+ ...updatableFields.content,
1133
+ // Deep merge metadata if it exists on both
1134
+ ...existingContent?.metadata && updatableFields.content.metadata ? {
1135
+ metadata: {
1136
+ ...existingContent.metadata,
1137
+ ...updatableFields.content.metadata
1138
+ }
1139
+ } : {}
1140
+ };
1141
+ setClauses.push(`content = ?`);
1142
+ values.push(JSON.stringify(newContent));
1143
+ delete updatableFields.content;
1144
+ }
1145
+ for (const key in updatableFields) {
1146
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
1147
+ const dbColumn = key === "threadId" ? "thread_id" : key;
1148
+ setClauses.push(`${dbColumn} = ?`);
1149
+ values.push(updatableFields[key]);
1150
+ }
1151
+ }
1152
+ if (setClauses.length > 0) {
1153
+ values.push(id);
1154
+ const updateQuery = `UPDATE ${fullTableName} SET ${setClauses.join(", ")} WHERE id = ?`;
1155
+ updateQueries.push({ sql: updateQuery, params: values });
1156
+ }
1157
+ }
1158
+ for (const query of updateQueries) {
1159
+ await this.operations.executeQuery(query);
1160
+ }
1161
+ if (threadIdsToUpdate.size > 0) {
1162
+ const threadPlaceholders = Array.from(threadIdsToUpdate).map(() => "?").join(",");
1163
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadPlaceholders})`;
1164
+ const threadUpdateParams = [(/* @__PURE__ */ new Date()).toISOString(), ...Array.from(threadIdsToUpdate)];
1165
+ await this.operations.executeQuery({ sql: threadUpdateQuery, params: threadUpdateParams });
1166
+ }
1167
+ const updatedMessages = await this.operations.executeQuery({ sql: selectQuery, params: messageIds });
1168
+ return updatedMessages.map((message) => {
1169
+ if (typeof message.content === "string") {
1170
+ try {
1171
+ message.content = JSON.parse(message.content);
1172
+ } catch {
1173
+ }
1174
+ }
1175
+ return message;
1176
+ });
1111
1177
  } catch (error$1) {
1112
1178
  throw new error.MastraError(
1113
1179
  {
1114
- id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1180
+ id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
1115
1181
  domain: error.ErrorDomain.STORAGE,
1116
1182
  category: error.ErrorCategory.THIRD_PARTY,
1117
- text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1118
- details: { workflowName, runId }
1183
+ details: { count: messages.length }
1119
1184
  },
1120
1185
  error$1
1121
1186
  );
1122
1187
  }
1123
1188
  }
1124
- async loadWorkflowSnapshot(params) {
1125
- const { workflowName, runId } = params;
1126
- this.logger.debug("Loading workflow snapshot", { workflowName, runId });
1189
+ };
1190
+ var StoreOperationsD1 = class extends storage.StoreOperations {
1191
+ client;
1192
+ binding;
1193
+ tablePrefix;
1194
+ constructor(config) {
1195
+ super();
1196
+ this.client = config.client;
1197
+ this.binding = config.binding;
1198
+ this.tablePrefix = config.tablePrefix || "";
1199
+ }
1200
+ async hasColumn(table, column) {
1201
+ const fullTableName = table.startsWith(this.tablePrefix) ? table : `${this.tablePrefix}${table}`;
1202
+ const sql = `PRAGMA table_info(${fullTableName});`;
1203
+ const result = await this.executeQuery({ sql, params: [] });
1204
+ if (!result || !Array.isArray(result)) return false;
1205
+ return result.some((col) => col.name === column || col.name === column.toLowerCase());
1206
+ }
1207
+ getTableName(tableName) {
1208
+ return `${this.tablePrefix}${tableName}`;
1209
+ }
1210
+ formatSqlParams(params) {
1211
+ return params.map((p) => p === void 0 || p === null ? null : p);
1212
+ }
1213
+ async executeWorkersBindingQuery({
1214
+ sql,
1215
+ params = [],
1216
+ first = false
1217
+ }) {
1218
+ if (!this.binding) {
1219
+ throw new Error("Workers binding is not configured");
1220
+ }
1127
1221
  try {
1128
- const d = await this.load({
1129
- tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1130
- keys: {
1131
- workflow_name: workflowName,
1132
- run_id: runId
1222
+ const statement = this.binding.prepare(sql);
1223
+ const formattedParams = this.formatSqlParams(params);
1224
+ let result;
1225
+ if (formattedParams.length > 0) {
1226
+ if (first) {
1227
+ result = await statement.bind(...formattedParams).first();
1228
+ if (!result) return null;
1229
+ return result;
1230
+ } else {
1231
+ result = await statement.bind(...formattedParams).all();
1232
+ const results = result.results || [];
1233
+ return results;
1133
1234
  }
1134
- });
1135
- return d ? d.snapshot : null;
1235
+ } else {
1236
+ if (first) {
1237
+ result = await statement.first();
1238
+ if (!result) return null;
1239
+ return result;
1240
+ } else {
1241
+ result = await statement.all();
1242
+ const results = result.results || [];
1243
+ return results;
1244
+ }
1245
+ }
1136
1246
  } catch (error$1) {
1137
1247
  throw new error.MastraError(
1138
1248
  {
1139
- id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1249
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1140
1250
  domain: error.ErrorDomain.STORAGE,
1141
1251
  category: error.ErrorCategory.THIRD_PARTY,
1142
- text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1143
- details: { workflowName, runId }
1252
+ details: { sql }
1253
+ },
1254
+ error$1
1255
+ );
1256
+ }
1257
+ }
1258
+ async executeRestQuery({
1259
+ sql,
1260
+ params = [],
1261
+ first = false
1262
+ }) {
1263
+ if (!this.client) {
1264
+ throw new Error("D1 client is not configured");
1265
+ }
1266
+ try {
1267
+ const formattedParams = this.formatSqlParams(params);
1268
+ const response = await this.client.query({
1269
+ sql,
1270
+ params: formattedParams
1271
+ });
1272
+ const result = response.result || [];
1273
+ const results = result.flatMap((r) => r.results || []);
1274
+ if (first) {
1275
+ return results[0] || null;
1276
+ }
1277
+ return results;
1278
+ } catch (error$1) {
1279
+ throw new error.MastraError(
1280
+ {
1281
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1282
+ domain: error.ErrorDomain.STORAGE,
1283
+ category: error.ErrorCategory.THIRD_PARTY,
1284
+ details: { sql }
1285
+ },
1286
+ error$1
1287
+ );
1288
+ }
1289
+ }
1290
+ async executeQuery(options) {
1291
+ if (this.binding) {
1292
+ return this.executeWorkersBindingQuery(options);
1293
+ } else if (this.client) {
1294
+ return this.executeRestQuery(options);
1295
+ } else {
1296
+ throw new Error("Neither binding nor client is configured");
1297
+ }
1298
+ }
1299
+ async getTableColumns(tableName) {
1300
+ try {
1301
+ const sql = `PRAGMA table_info(${tableName})`;
1302
+ const result = await this.executeQuery({ sql });
1303
+ if (!result || !Array.isArray(result)) {
1304
+ return [];
1305
+ }
1306
+ return result.map((row) => ({
1307
+ name: row.name,
1308
+ type: row.type
1309
+ }));
1310
+ } catch (error) {
1311
+ this.logger.warn(`Failed to get table columns for ${tableName}:`, error);
1312
+ return [];
1313
+ }
1314
+ }
1315
+ serializeValue(value) {
1316
+ if (value === null || value === void 0) {
1317
+ return null;
1318
+ }
1319
+ if (value instanceof Date) {
1320
+ return value.toISOString();
1321
+ }
1322
+ if (typeof value === "object") {
1323
+ return JSON.stringify(value);
1324
+ }
1325
+ return value;
1326
+ }
1327
+ getSqlType(type) {
1328
+ switch (type) {
1329
+ case "bigint":
1330
+ return "INTEGER";
1331
+ // SQLite uses INTEGER for all integer sizes
1332
+ case "jsonb":
1333
+ return "TEXT";
1334
+ // Store JSON as TEXT in SQLite
1335
+ default:
1336
+ return super.getSqlType(type);
1337
+ }
1338
+ }
1339
+ async createTable({
1340
+ tableName,
1341
+ schema
1342
+ }) {
1343
+ try {
1344
+ const fullTableName = this.getTableName(tableName);
1345
+ const columnDefinitions = Object.entries(schema).map(([colName, colDef]) => {
1346
+ const type = this.getSqlType(colDef.type);
1347
+ const nullable = colDef.nullable === false ? "NOT NULL" : "";
1348
+ const primaryKey = colDef.primaryKey ? "PRIMARY KEY" : "";
1349
+ return `${colName} ${type} ${nullable} ${primaryKey}`.trim();
1350
+ });
1351
+ const tableConstraints = [];
1352
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
1353
+ tableConstraints.push("UNIQUE (workflow_name, run_id)");
1354
+ }
1355
+ const query = createSqlBuilder().createTable(fullTableName, columnDefinitions, tableConstraints);
1356
+ const { sql, params } = query.build();
1357
+ await this.executeQuery({ sql, params });
1358
+ this.logger.debug(`Created table ${fullTableName}`);
1359
+ } catch (error$1) {
1360
+ throw new error.MastraError(
1361
+ {
1362
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1363
+ domain: error.ErrorDomain.STORAGE,
1364
+ category: error.ErrorCategory.THIRD_PARTY,
1365
+ details: { tableName }
1366
+ },
1367
+ error$1
1368
+ );
1369
+ }
1370
+ }
1371
+ async clearTable({ tableName }) {
1372
+ try {
1373
+ const fullTableName = this.getTableName(tableName);
1374
+ const query = createSqlBuilder().delete(fullTableName);
1375
+ const { sql, params } = query.build();
1376
+ await this.executeQuery({ sql, params });
1377
+ this.logger.debug(`Cleared table ${fullTableName}`);
1378
+ } catch (error$1) {
1379
+ throw new error.MastraError(
1380
+ {
1381
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1382
+ domain: error.ErrorDomain.STORAGE,
1383
+ category: error.ErrorCategory.THIRD_PARTY,
1384
+ details: { tableName }
1385
+ },
1386
+ error$1
1387
+ );
1388
+ }
1389
+ }
1390
+ async dropTable({ tableName }) {
1391
+ try {
1392
+ const fullTableName = this.getTableName(tableName);
1393
+ const sql = `DROP TABLE IF EXISTS ${fullTableName}`;
1394
+ await this.executeQuery({ sql });
1395
+ this.logger.debug(`Dropped table ${fullTableName}`);
1396
+ } catch (error$1) {
1397
+ throw new error.MastraError(
1398
+ {
1399
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1400
+ domain: error.ErrorDomain.STORAGE,
1401
+ category: error.ErrorCategory.THIRD_PARTY,
1402
+ details: { tableName }
1403
+ },
1404
+ error$1
1405
+ );
1406
+ }
1407
+ }
1408
+ async alterTable(args) {
1409
+ try {
1410
+ const fullTableName = this.getTableName(args.tableName);
1411
+ const existingColumns = await this.getTableColumns(fullTableName);
1412
+ const existingColumnNames = new Set(existingColumns.map((col) => col.name));
1413
+ for (const [columnName, column] of Object.entries(args.schema)) {
1414
+ if (!existingColumnNames.has(columnName) && args.ifNotExists.includes(columnName)) {
1415
+ const sqlType = this.getSqlType(column.type);
1416
+ const defaultValue = this.getDefaultValue(column.type);
1417
+ const sql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${defaultValue}`;
1418
+ await this.executeQuery({ sql });
1419
+ this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
1420
+ }
1421
+ }
1422
+ } catch (error$1) {
1423
+ throw new error.MastraError(
1424
+ {
1425
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1426
+ domain: error.ErrorDomain.STORAGE,
1427
+ category: error.ErrorCategory.THIRD_PARTY,
1428
+ details: { tableName: args.tableName }
1429
+ },
1430
+ error$1
1431
+ );
1432
+ }
1433
+ }
1434
+ async insert({ tableName, record }) {
1435
+ try {
1436
+ const fullTableName = this.getTableName(tableName);
1437
+ const processedRecord = await this.processRecord(record);
1438
+ const columns = Object.keys(processedRecord);
1439
+ const values = Object.values(processedRecord);
1440
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1441
+ const { sql, params } = query.build();
1442
+ await this.executeQuery({ sql, params });
1443
+ } catch (error$1) {
1444
+ throw new error.MastraError(
1445
+ {
1446
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1447
+ domain: error.ErrorDomain.STORAGE,
1448
+ category: error.ErrorCategory.THIRD_PARTY,
1449
+ details: { tableName }
1144
1450
  },
1145
1451
  error$1
1146
1452
  );
1147
1453
  }
1148
1454
  }
1149
- /**
1150
- * Insert multiple records in a batch operation
1151
- * @param tableName The table to insert into
1152
- * @param records The records to insert
1153
- */
1154
1455
  async batchInsert({ tableName, records }) {
1155
- if (records.length === 0) return;
1156
- const fullTableName = this.getTableName(tableName);
1157
1456
  try {
1158
- const batchSize = 50;
1159
- for (let i = 0; i < records.length; i += batchSize) {
1160
- const batch = records.slice(i, i + batchSize);
1161
- const recordsToInsert = batch;
1162
- if (recordsToInsert.length > 0) {
1163
- const firstRecord = recordsToInsert[0];
1164
- const columns = Object.keys(firstRecord || {});
1165
- for (const record of recordsToInsert) {
1166
- const values = columns.map((col) => {
1167
- if (!record) return null;
1168
- const value = typeof col === "string" ? record[col] : null;
1169
- return this.serializeValue(value);
1170
- });
1171
- const query = createSqlBuilder().insert(fullTableName, columns, values);
1172
- const { sql, params } = query.build();
1173
- await this.executeQuery({ sql, params });
1174
- }
1457
+ if (records.length === 0) return;
1458
+ const fullTableName = this.getTableName(tableName);
1459
+ const processedRecords = await Promise.all(records.map((record) => this.processRecord(record)));
1460
+ const columns = Object.keys(processedRecords[0] || {});
1461
+ for (const record of processedRecords) {
1462
+ const values = Object.values(record);
1463
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1464
+ const { sql, params } = query.build();
1465
+ await this.executeQuery({ sql, params });
1466
+ }
1467
+ } catch (error$1) {
1468
+ throw new error.MastraError(
1469
+ {
1470
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1471
+ domain: error.ErrorDomain.STORAGE,
1472
+ category: error.ErrorCategory.THIRD_PARTY,
1473
+ details: { tableName }
1474
+ },
1475
+ error$1
1476
+ );
1477
+ }
1478
+ }
1479
+ async load({ tableName, keys }) {
1480
+ try {
1481
+ const fullTableName = this.getTableName(tableName);
1482
+ const query = createSqlBuilder().select("*").from(fullTableName);
1483
+ let firstKey = true;
1484
+ for (const [key, value] of Object.entries(keys)) {
1485
+ if (firstKey) {
1486
+ query.where(`${key} = ?`, value);
1487
+ firstKey = false;
1488
+ } else {
1489
+ query.andWhere(`${key} = ?`, value);
1175
1490
  }
1176
- this.logger.debug(
1177
- `Processed batch ${Math.floor(i / batchSize) + 1} of ${Math.ceil(records.length / batchSize)}`
1178
- );
1179
1491
  }
1180
- this.logger.debug(`Successfully batch inserted ${records.length} records into ${tableName}`);
1492
+ query.orderBy("createdAt", "DESC");
1493
+ query.limit(1);
1494
+ const { sql, params } = query.build();
1495
+ const result = await this.executeQuery({ sql, params, first: true });
1496
+ if (!result) {
1497
+ return null;
1498
+ }
1499
+ const deserializedResult = {};
1500
+ for (const [key, value] of Object.entries(result)) {
1501
+ deserializedResult[key] = deserializeValue(value);
1502
+ }
1503
+ return deserializedResult;
1181
1504
  } catch (error$1) {
1182
1505
  throw new error.MastraError(
1183
1506
  {
1184
- id: "CLOUDFLARE_D1_STORAGE_BATCH_INSERT_ERROR",
1507
+ id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1185
1508
  domain: error.ErrorDomain.STORAGE,
1186
1509
  category: error.ErrorCategory.THIRD_PARTY,
1187
- text: `Failed to batch insert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1188
1510
  details: { tableName }
1189
1511
  },
1190
1512
  error$1
1191
1513
  );
1192
1514
  }
1193
1515
  }
1516
+ async processRecord(record) {
1517
+ const processed = {};
1518
+ for (const [key, value] of Object.entries(record)) {
1519
+ processed[key] = this.serializeValue(value);
1520
+ }
1521
+ return processed;
1522
+ }
1194
1523
  /**
1195
1524
  * Upsert multiple records in a batch operation
1196
1525
  * @param tableName The table to insert into
1197
1526
  * @param records The records to insert
1198
1527
  */
1199
- async batchUpsert({
1200
- tableName,
1201
- records
1202
- }) {
1528
+ async batchUpsert({ tableName, records }) {
1203
1529
  if (records.length === 0) return;
1204
1530
  const fullTableName = this.getTableName(tableName);
1205
1531
  try {
@@ -1246,73 +1572,349 @@ var D1Store = class extends storage.MastraStorage {
1246
1572
  );
1247
1573
  }
1248
1574
  }
1249
- /**
1250
- * @deprecated use getTracesPaginated instead
1251
- */
1252
- async getTraces({
1253
- name,
1254
- scope,
1255
- page,
1256
- perPage,
1257
- attributes,
1258
- fromDate,
1259
- toDate
1575
+ };
1576
+ function transformScoreRow(row) {
1577
+ const deserialized = { ...row };
1578
+ deserialized.input = storage.safelyParseJSON(row.input);
1579
+ deserialized.output = storage.safelyParseJSON(row.output);
1580
+ deserialized.scorer = storage.safelyParseJSON(row.scorer);
1581
+ deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1582
+ deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1583
+ deserialized.metadata = storage.safelyParseJSON(row.metadata);
1584
+ deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1585
+ deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1586
+ deserialized.entity = storage.safelyParseJSON(row.entity);
1587
+ deserialized.createdAt = row.createdAtZ || row.createdAt;
1588
+ deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1589
+ return deserialized;
1590
+ }
1591
+ var ScoresStorageD1 = class extends storage.ScoresStorage {
1592
+ operations;
1593
+ constructor({ operations }) {
1594
+ super();
1595
+ this.operations = operations;
1596
+ }
1597
+ async getScoreById({ id }) {
1598
+ try {
1599
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1600
+ const query = createSqlBuilder().select("*").from(fullTableName).where("id = ?", id);
1601
+ const { sql, params } = query.build();
1602
+ const result = await this.operations.executeQuery({ sql, params, first: true });
1603
+ if (!result) {
1604
+ return null;
1605
+ }
1606
+ return transformScoreRow(result);
1607
+ } catch (error$1) {
1608
+ throw new error.MastraError(
1609
+ {
1610
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1611
+ domain: error.ErrorDomain.STORAGE,
1612
+ category: error.ErrorCategory.THIRD_PARTY
1613
+ },
1614
+ error$1
1615
+ );
1616
+ }
1617
+ }
1618
+ async saveScore(score) {
1619
+ let parsedScore;
1620
+ try {
1621
+ parsedScore = scores.saveScorePayloadSchema.parse(score);
1622
+ } catch (error$1) {
1623
+ throw new error.MastraError(
1624
+ {
1625
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1626
+ domain: error.ErrorDomain.STORAGE,
1627
+ category: error.ErrorCategory.USER,
1628
+ details: { scoreId: score.id }
1629
+ },
1630
+ error$1
1631
+ );
1632
+ }
1633
+ try {
1634
+ const id = crypto.randomUUID();
1635
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1636
+ const serializedRecord = {};
1637
+ for (const [key, value] of Object.entries(parsedScore)) {
1638
+ if (value !== null && value !== void 0) {
1639
+ if (typeof value === "object") {
1640
+ serializedRecord[key] = JSON.stringify(value);
1641
+ } else {
1642
+ serializedRecord[key] = value;
1643
+ }
1644
+ } else {
1645
+ serializedRecord[key] = null;
1646
+ }
1647
+ }
1648
+ serializedRecord.id = id;
1649
+ serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1650
+ serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1651
+ const columns = Object.keys(serializedRecord);
1652
+ const values = Object.values(serializedRecord);
1653
+ const query = createSqlBuilder().insert(fullTableName, columns, values);
1654
+ const { sql, params } = query.build();
1655
+ await this.operations.executeQuery({ sql, params });
1656
+ const scoreFromDb = await this.getScoreById({ id });
1657
+ return { score: scoreFromDb };
1658
+ } catch (error$1) {
1659
+ throw new error.MastraError(
1660
+ {
1661
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1662
+ domain: error.ErrorDomain.STORAGE,
1663
+ category: error.ErrorCategory.THIRD_PARTY
1664
+ },
1665
+ error$1
1666
+ );
1667
+ }
1668
+ }
1669
+ async getScoresByScorerId({
1670
+ scorerId,
1671
+ entityId,
1672
+ entityType,
1673
+ source,
1674
+ pagination
1260
1675
  }) {
1261
- const fullTableName = this.getTableName(storage.TABLE_TRACES);
1262
1676
  try {
1263
- const query = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1264
- if (name) {
1265
- query.andWhere("name LIKE ?", `%${name}%`);
1677
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1678
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1679
+ if (entityId) {
1680
+ countQuery.andWhere("entityId = ?", entityId);
1266
1681
  }
1267
- if (scope) {
1268
- query.andWhere("scope = ?", scope);
1682
+ if (entityType) {
1683
+ countQuery.andWhere("entityType = ?", entityType);
1269
1684
  }
1270
- if (attributes && Object.keys(attributes).length > 0) {
1271
- for (const [key, value] of Object.entries(attributes)) {
1272
- query.jsonLike("attributes", key, value);
1273
- }
1685
+ if (source) {
1686
+ countQuery.andWhere("source = ?", source);
1274
1687
  }
1275
- if (fromDate) {
1276
- query.andWhere("createdAt >= ?", fromDate instanceof Date ? fromDate.toISOString() : fromDate);
1688
+ const countResult = await this.operations.executeQuery(countQuery.build());
1689
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1690
+ if (total === 0) {
1691
+ return {
1692
+ pagination: {
1693
+ total: 0,
1694
+ page: pagination.page,
1695
+ perPage: pagination.perPage,
1696
+ hasMore: false
1697
+ },
1698
+ scores: []
1699
+ };
1277
1700
  }
1278
- if (toDate) {
1279
- query.andWhere("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
1701
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1702
+ if (entityId) {
1703
+ selectQuery.andWhere("entityId = ?", entityId);
1280
1704
  }
1281
- query.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1282
- const { sql, params } = query.build();
1283
- const results = await this.executeQuery({ sql, params });
1284
- return isArrayOfRecords(results) ? results.map(
1285
- (trace) => ({
1286
- ...trace,
1287
- attributes: this.deserializeValue(trace.attributes, "jsonb"),
1288
- status: this.deserializeValue(trace.status, "jsonb"),
1289
- events: this.deserializeValue(trace.events, "jsonb"),
1290
- links: this.deserializeValue(trace.links, "jsonb"),
1291
- other: this.deserializeValue(trace.other, "jsonb")
1292
- })
1293
- ) : [];
1705
+ if (entityType) {
1706
+ selectQuery.andWhere("entityType = ?", entityType);
1707
+ }
1708
+ if (source) {
1709
+ selectQuery.andWhere("source = ?", source);
1710
+ }
1711
+ selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1712
+ const { sql, params } = selectQuery.build();
1713
+ const results = await this.operations.executeQuery({ sql, params });
1714
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1715
+ return {
1716
+ pagination: {
1717
+ total,
1718
+ page: pagination.page,
1719
+ perPage: pagination.perPage,
1720
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1721
+ },
1722
+ scores
1723
+ };
1294
1724
  } catch (error$1) {
1295
- const mastraError = new error.MastraError(
1725
+ throw new error.MastraError(
1726
+ {
1727
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1728
+ domain: error.ErrorDomain.STORAGE,
1729
+ category: error.ErrorCategory.THIRD_PARTY
1730
+ },
1731
+ error$1
1732
+ );
1733
+ }
1734
+ }
1735
+ async getScoresByRunId({
1736
+ runId,
1737
+ pagination
1738
+ }) {
1739
+ try {
1740
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1741
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1742
+ const countResult = await this.operations.executeQuery(countQuery.build());
1743
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1744
+ if (total === 0) {
1745
+ return {
1746
+ pagination: {
1747
+ total: 0,
1748
+ page: pagination.page,
1749
+ perPage: pagination.perPage,
1750
+ hasMore: false
1751
+ },
1752
+ scores: []
1753
+ };
1754
+ }
1755
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1756
+ const { sql, params } = selectQuery.build();
1757
+ const results = await this.operations.executeQuery({ sql, params });
1758
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1759
+ return {
1760
+ pagination: {
1761
+ total,
1762
+ page: pagination.page,
1763
+ perPage: pagination.perPage,
1764
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1765
+ },
1766
+ scores
1767
+ };
1768
+ } catch (error$1) {
1769
+ throw new error.MastraError(
1770
+ {
1771
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1772
+ domain: error.ErrorDomain.STORAGE,
1773
+ category: error.ErrorCategory.THIRD_PARTY
1774
+ },
1775
+ error$1
1776
+ );
1777
+ }
1778
+ }
1779
+ async getScoresByEntityId({
1780
+ entityId,
1781
+ entityType,
1782
+ pagination
1783
+ }) {
1784
+ try {
1785
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1786
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1787
+ const countResult = await this.operations.executeQuery(countQuery.build());
1788
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1789
+ if (total === 0) {
1790
+ return {
1791
+ pagination: {
1792
+ total: 0,
1793
+ page: pagination.page,
1794
+ perPage: pagination.perPage,
1795
+ hasMore: false
1796
+ },
1797
+ scores: []
1798
+ };
1799
+ }
1800
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1801
+ const { sql, params } = selectQuery.build();
1802
+ const results = await this.operations.executeQuery({ sql, params });
1803
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1804
+ return {
1805
+ pagination: {
1806
+ total,
1807
+ page: pagination.page,
1808
+ perPage: pagination.perPage,
1809
+ hasMore: total > (pagination.page + 1) * pagination.perPage
1810
+ },
1811
+ scores
1812
+ };
1813
+ } catch (error$1) {
1814
+ throw new error.MastraError(
1815
+ {
1816
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1817
+ domain: error.ErrorDomain.STORAGE,
1818
+ category: error.ErrorCategory.THIRD_PARTY
1819
+ },
1820
+ error$1
1821
+ );
1822
+ }
1823
+ }
1824
+ async getScoresBySpan({
1825
+ traceId,
1826
+ spanId,
1827
+ pagination
1828
+ }) {
1829
+ try {
1830
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1831
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1832
+ const countResult = await this.operations.executeQuery(countQuery.build());
1833
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1834
+ if (total === 0) {
1835
+ return {
1836
+ pagination: {
1837
+ total: 0,
1838
+ page: pagination.page,
1839
+ perPage: pagination.perPage,
1840
+ hasMore: false
1841
+ },
1842
+ scores: []
1843
+ };
1844
+ }
1845
+ const limit = pagination.perPage + 1;
1846
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limit).offset(pagination.page * pagination.perPage);
1847
+ const { sql, params } = selectQuery.build();
1848
+ const results = await this.operations.executeQuery({ sql, params });
1849
+ const rows = Array.isArray(results) ? results : [];
1850
+ const scores = rows.slice(0, pagination.perPage).map(transformScoreRow);
1851
+ return {
1852
+ pagination: {
1853
+ total,
1854
+ page: pagination.page,
1855
+ perPage: pagination.perPage,
1856
+ hasMore: rows.length > pagination.perPage
1857
+ },
1858
+ scores
1859
+ };
1860
+ } catch (error$1) {
1861
+ throw new error.MastraError(
1862
+ {
1863
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1864
+ domain: error.ErrorDomain.STORAGE,
1865
+ category: error.ErrorCategory.THIRD_PARTY
1866
+ },
1867
+ error$1
1868
+ );
1869
+ }
1870
+ }
1871
+ };
1872
+ function isArrayOfRecords2(value) {
1873
+ return value && Array.isArray(value) && value.length > 0;
1874
+ }
1875
+ var TracesStorageD1 = class extends storage.TracesStorage {
1876
+ operations;
1877
+ constructor({ operations }) {
1878
+ super();
1879
+ this.operations = operations;
1880
+ }
1881
+ async getTraces(args) {
1882
+ const paginatedArgs = {
1883
+ name: args.name,
1884
+ scope: args.scope,
1885
+ page: args.page,
1886
+ perPage: args.perPage,
1887
+ attributes: args.attributes,
1888
+ filters: args.filters,
1889
+ dateRange: args.fromDate || args.toDate ? {
1890
+ start: args.fromDate,
1891
+ end: args.toDate
1892
+ } : void 0
1893
+ };
1894
+ try {
1895
+ const result = await this.getTracesPaginated(paginatedArgs);
1896
+ return result.traces;
1897
+ } catch (error$1) {
1898
+ throw new error.MastraError(
1296
1899
  {
1297
1900
  id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1298
1901
  domain: error.ErrorDomain.STORAGE,
1299
1902
  category: error.ErrorCategory.THIRD_PARTY,
1300
1903
  text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1301
1904
  details: {
1302
- name: name ?? "",
1303
- scope: scope ?? ""
1905
+ name: args.name ?? "",
1906
+ scope: args.scope ?? ""
1304
1907
  }
1305
1908
  },
1306
1909
  error$1
1307
1910
  );
1308
- this.logger?.error(mastraError.toString());
1309
- this.logger?.trackException(mastraError);
1310
- return [];
1311
1911
  }
1312
1912
  }
1313
1913
  async getTracesPaginated(args) {
1314
- const { name, scope, page, perPage, attributes, fromDate, toDate } = args;
1315
- const fullTableName = this.getTableName(storage.TABLE_TRACES);
1914
+ const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1915
+ const fromDate = dateRange?.start;
1916
+ const toDate = dateRange?.end;
1917
+ const fullTableName = this.operations.getTableName(storage.TABLE_TRACES);
1316
1918
  try {
1317
1919
  const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1318
1920
  const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
@@ -1340,18 +1942,22 @@ var D1Store = class extends storage.MastraStorage {
1340
1942
  dataQuery.andWhere("createdAt <= ?", toDateStr);
1341
1943
  countQuery.andWhere("createdAt <= ?", toDateStr);
1342
1944
  }
1343
- const countResult = await this.executeQuery(countQuery.build());
1945
+ const allDataResult = await this.operations.executeQuery(
1946
+ createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1947
+ );
1948
+ console.info("allDataResult", allDataResult);
1949
+ const countResult = await this.operations.executeQuery(countQuery.build());
1344
1950
  const total = Number(countResult?.[0]?.count ?? 0);
1345
1951
  dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1346
- const results = await this.executeQuery(dataQuery.build());
1347
- const traces = isArrayOfRecords(results) ? results.map(
1952
+ const results = await this.operations.executeQuery(dataQuery.build());
1953
+ const traces = isArrayOfRecords2(results) ? results.map(
1348
1954
  (trace) => ({
1349
1955
  ...trace,
1350
- attributes: this.deserializeValue(trace.attributes, "jsonb"),
1351
- status: this.deserializeValue(trace.status, "jsonb"),
1352
- events: this.deserializeValue(trace.events, "jsonb"),
1353
- links: this.deserializeValue(trace.links, "jsonb"),
1354
- other: this.deserializeValue(trace.other, "jsonb")
1956
+ attributes: deserializeValue(trace.attributes, "jsonb"),
1957
+ status: deserializeValue(trace.status, "jsonb"),
1958
+ events: deserializeValue(trace.events, "jsonb"),
1959
+ links: deserializeValue(trace.links, "jsonb"),
1960
+ other: deserializeValue(trace.other, "jsonb")
1355
1961
  })
1356
1962
  ) : [];
1357
1963
  return {
@@ -1364,7 +1970,7 @@ var D1Store = class extends storage.MastraStorage {
1364
1970
  } catch (error$1) {
1365
1971
  const mastraError = new error.MastraError(
1366
1972
  {
1367
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1973
+ id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1368
1974
  domain: error.ErrorDomain.STORAGE,
1369
1975
  category: error.ErrorCategory.THIRD_PARTY,
1370
1976
  text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -1377,142 +1983,106 @@ var D1Store = class extends storage.MastraStorage {
1377
1983
  return { traces: [], total: 0, page, perPage, hasMore: false };
1378
1984
  }
1379
1985
  }
1380
- /**
1381
- * @deprecated use getEvals instead
1382
- */
1383
- async getEvalsByAgentName(agentName, type) {
1384
- const fullTableName = this.getTableName(storage.TABLE_EVALS);
1385
- try {
1386
- let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
1387
- if (type === "test") {
1388
- query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
1389
- } else if (type === "live") {
1390
- query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
1391
- }
1392
- query.orderBy("created_at", "DESC");
1393
- const { sql, params } = query.build();
1394
- const results = await this.executeQuery({ sql, params });
1395
- return isArrayOfRecords(results) ? results.map((row) => {
1396
- const result = this.deserializeValue(row.result);
1397
- const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
1398
- return {
1399
- input: row.input || "",
1400
- output: row.output || "",
1401
- result,
1402
- agentName: row.agent_name || "",
1403
- metricName: row.metric_name || "",
1404
- instructions: row.instructions || "",
1405
- runId: row.run_id || "",
1406
- globalRunId: row.global_run_id || "",
1407
- createdAt: row.created_at || "",
1408
- testInfo
1409
- };
1410
- }) : [];
1411
- } catch (error$1) {
1412
- const mastraError = new error.MastraError(
1413
- {
1414
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
1415
- domain: error.ErrorDomain.STORAGE,
1416
- category: error.ErrorCategory.THIRD_PARTY,
1417
- text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1418
- details: { agentName }
1419
- },
1420
- error$1
1421
- );
1422
- this.logger?.error(mastraError.toString());
1423
- this.logger?.trackException(mastraError);
1424
- return [];
1425
- }
1986
+ async batchTraceInsert({ records }) {
1987
+ this.logger.debug("Batch inserting traces", { count: records.length });
1988
+ await this.operations.batchInsert({
1989
+ tableName: storage.TABLE_TRACES,
1990
+ records
1991
+ });
1426
1992
  }
1427
- async getEvals(options) {
1428
- const { agentName, type, page = 0, perPage = 40, fromDate, toDate } = options || {};
1429
- const fullTableName = this.getTableName(storage.TABLE_EVALS);
1430
- const conditions = [];
1431
- const queryParams = [];
1432
- if (agentName) {
1433
- conditions.push(`agent_name = ?`);
1434
- queryParams.push(agentName);
1435
- }
1436
- if (type === "test") {
1437
- conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
1438
- } else if (type === "live") {
1439
- conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
1440
- }
1441
- if (fromDate) {
1442
- conditions.push(`createdAt >= ?`);
1443
- queryParams.push(this.serializeDate(fromDate));
1444
- }
1445
- if (toDate) {
1446
- conditions.push(`createdAt <= ?`);
1447
- queryParams.push(this.serializeDate(toDate));
1448
- }
1449
- const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
1450
- if (conditions.length > 0) {
1451
- countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
1452
- }
1453
- const { sql: countSql, params: countParams } = countQueryBuilder.build();
1993
+ };
1994
+ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1995
+ operations;
1996
+ constructor({ operations }) {
1997
+ super();
1998
+ this.operations = operations;
1999
+ }
2000
+ updateWorkflowResults({
2001
+ // workflowName,
2002
+ // runId,
2003
+ // stepId,
2004
+ // result,
2005
+ // runtimeContext,
2006
+ }) {
2007
+ throw new Error("Method not implemented.");
2008
+ }
2009
+ updateWorkflowState({
2010
+ // workflowName,
2011
+ // runId,
2012
+ // opts,
2013
+ }) {
2014
+ throw new Error("Method not implemented.");
2015
+ }
2016
+ async persistWorkflowSnapshot({
2017
+ workflowName,
2018
+ runId,
2019
+ resourceId,
2020
+ snapshot
2021
+ }) {
2022
+ const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
2023
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2024
+ const currentSnapshot = await this.operations.load({
2025
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
2026
+ keys: { workflow_name: workflowName, run_id: runId }
2027
+ });
2028
+ const persisting = currentSnapshot ? {
2029
+ ...currentSnapshot,
2030
+ resourceId,
2031
+ snapshot: JSON.stringify(snapshot),
2032
+ updatedAt: now
2033
+ } : {
2034
+ workflow_name: workflowName,
2035
+ run_id: runId,
2036
+ resourceId,
2037
+ snapshot,
2038
+ createdAt: now,
2039
+ updatedAt: now
2040
+ };
2041
+ const processedRecord = await this.operations.processRecord(persisting);
2042
+ const columns = Object.keys(processedRecord);
2043
+ const values = Object.values(processedRecord);
2044
+ const updateMap = {
2045
+ snapshot: "excluded.snapshot",
2046
+ updatedAt: "excluded.updatedAt"
2047
+ };
2048
+ this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2049
+ const query = createSqlBuilder().insert(fullTableName, columns, values, ["workflow_name", "run_id"], updateMap);
2050
+ const { sql, params } = query.build();
1454
2051
  try {
1455
- const countResult = await this.executeQuery({
1456
- sql: countSql,
1457
- params: countParams,
1458
- first: true
1459
- });
1460
- const total = Number(countResult?.count || 0);
1461
- const currentOffset = page * perPage;
1462
- if (total === 0) {
1463
- return {
1464
- evals: [],
1465
- total: 0,
1466
- page,
1467
- perPage,
1468
- hasMore: false
1469
- };
1470
- }
1471
- const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
1472
- if (conditions.length > 0) {
1473
- dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
1474
- }
1475
- dataQueryBuilder.orderBy("createdAt", "DESC").limit(perPage).offset(currentOffset);
1476
- const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
1477
- const rows = await this.executeQuery({
1478
- sql: dataSql,
1479
- params: dataParams
1480
- });
1481
- const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
1482
- const result = this.deserializeValue(row.result);
1483
- const testInfo = row.test_info ? this.deserializeValue(row.test_info) : void 0;
1484
- if (!result || typeof result !== "object" || !("score" in result)) {
1485
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
2052
+ await this.operations.executeQuery({ sql, params });
2053
+ } catch (error$1) {
2054
+ throw new error.MastraError(
2055
+ {
2056
+ id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
2057
+ domain: error.ErrorDomain.STORAGE,
2058
+ category: error.ErrorCategory.THIRD_PARTY,
2059
+ text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
2060
+ details: { workflowName, runId }
2061
+ },
2062
+ error$1
2063
+ );
2064
+ }
2065
+ }
2066
+ async loadWorkflowSnapshot(params) {
2067
+ const { workflowName, runId } = params;
2068
+ this.logger.debug("Loading workflow snapshot", { workflowName, runId });
2069
+ try {
2070
+ const d = await this.operations.load({
2071
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
2072
+ keys: {
2073
+ workflow_name: workflowName,
2074
+ run_id: runId
1486
2075
  }
1487
- return {
1488
- input: row.input,
1489
- output: row.output,
1490
- result,
1491
- agentName: row.agent_name,
1492
- metricName: row.metric_name,
1493
- instructions: row.instructions,
1494
- testInfo,
1495
- globalRunId: row.global_run_id,
1496
- runId: row.run_id,
1497
- createdAt: row.createdAt
1498
- };
1499
2076
  });
1500
- const hasMore = currentOffset + evals.length < total;
1501
- return {
1502
- evals,
1503
- total,
1504
- page,
1505
- perPage,
1506
- hasMore
1507
- };
2077
+ return d ? d.snapshot : null;
1508
2078
  } catch (error$1) {
1509
2079
  throw new error.MastraError(
1510
2080
  {
1511
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
2081
+ id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1512
2082
  domain: error.ErrorDomain.STORAGE,
1513
2083
  category: error.ErrorCategory.THIRD_PARTY,
1514
- text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1515
- details: { agentName: agentName ?? "", type: type ?? "" }
2084
+ text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
2085
+ details: { workflowName, runId }
1516
2086
  },
1517
2087
  error$1
1518
2088
  );
@@ -1531,17 +2101,11 @@ var D1Store = class extends storage.MastraStorage {
1531
2101
  workflowName: row.workflow_name,
1532
2102
  runId: row.run_id,
1533
2103
  snapshot: parsedSnapshot,
1534
- createdAt: this.ensureDate(row.createdAt),
1535
- updatedAt: this.ensureDate(row.updatedAt),
2104
+ createdAt: storage.ensureDate(row.createdAt),
2105
+ updatedAt: storage.ensureDate(row.updatedAt),
1536
2106
  resourceId: row.resourceId
1537
2107
  };
1538
2108
  }
1539
- async hasColumn(table, column) {
1540
- const sql = `PRAGMA table_info(${table});`;
1541
- const result = await this.executeQuery({ sql, params: [] });
1542
- if (!result || !Array.isArray(result)) return false;
1543
- return result.some((col) => col.name === column || col.name === column.toLowerCase());
1544
- }
1545
2109
  async getWorkflowRuns({
1546
2110
  workflowName,
1547
2111
  fromDate,
@@ -1550,13 +2114,13 @@ var D1Store = class extends storage.MastraStorage {
1550
2114
  offset,
1551
2115
  resourceId
1552
2116
  } = {}) {
1553
- const fullTableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
2117
+ const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1554
2118
  try {
1555
2119
  const builder = createSqlBuilder().select().from(fullTableName);
1556
2120
  const countBuilder = createSqlBuilder().count().from(fullTableName);
1557
2121
  if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
1558
2122
  if (resourceId) {
1559
- const hasResourceId = await this.hasColumn(fullTableName, "resourceId");
2123
+ const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
1560
2124
  if (hasResourceId) {
1561
2125
  builder.whereAnd("resourceId = ?", resourceId);
1562
2126
  countBuilder.whereAnd("resourceId = ?", resourceId);
@@ -1579,14 +2143,14 @@ var D1Store = class extends storage.MastraStorage {
1579
2143
  let total = 0;
1580
2144
  if (limit !== void 0 && offset !== void 0) {
1581
2145
  const { sql: countSql, params: countParams } = countBuilder.build();
1582
- const countResult = await this.executeQuery({
2146
+ const countResult = await this.operations.executeQuery({
1583
2147
  sql: countSql,
1584
2148
  params: countParams,
1585
2149
  first: true
1586
2150
  });
1587
2151
  total = Number(countResult?.count ?? 0);
1588
2152
  }
1589
- const results = await this.executeQuery({ sql, params });
2153
+ const results = await this.operations.executeQuery({ sql, params });
1590
2154
  const runs = (isArrayOfRecords(results) ? results : []).map((row) => this.parseWorkflowRun(row));
1591
2155
  return { runs, total: total || runs.length };
1592
2156
  } catch (error$1) {
@@ -1609,7 +2173,7 @@ var D1Store = class extends storage.MastraStorage {
1609
2173
  runId,
1610
2174
  workflowName
1611
2175
  }) {
1612
- const fullTableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
2176
+ const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1613
2177
  try {
1614
2178
  const conditions = [];
1615
2179
  const params = [];
@@ -1623,7 +2187,7 @@ var D1Store = class extends storage.MastraStorage {
1623
2187
  }
1624
2188
  const whereClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
1625
2189
  const sql = `SELECT * FROM ${fullTableName} ${whereClause} ORDER BY createdAt DESC LIMIT 1`;
1626
- const result = await this.executeQuery({ sql, params, first: true });
2190
+ const result = await this.operations.executeQuery({ sql, params, first: true });
1627
2191
  if (!result) return null;
1628
2192
  return this.parseWorkflowRun(result);
1629
2193
  } catch (error$1) {
@@ -1639,6 +2203,312 @@ var D1Store = class extends storage.MastraStorage {
1639
2203
  );
1640
2204
  }
1641
2205
  }
2206
+ };
2207
+
2208
+ // src/storage/index.ts
2209
+ var D1Store = class extends storage.MastraStorage {
2210
+ client;
2211
+ binding;
2212
+ // D1Database binding
2213
+ tablePrefix;
2214
+ stores;
2215
+ /**
2216
+ * Creates a new D1Store instance
2217
+ * @param config Configuration for D1 access (either REST API or Workers Binding API)
2218
+ */
2219
+ constructor(config) {
2220
+ try {
2221
+ super({ name: "D1" });
2222
+ if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2223
+ throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2224
+ }
2225
+ this.tablePrefix = config.tablePrefix || "";
2226
+ if ("binding" in config) {
2227
+ if (!config.binding) {
2228
+ throw new Error("D1 binding is required when using Workers Binding API");
2229
+ }
2230
+ this.binding = config.binding;
2231
+ this.logger.info("Using D1 Workers Binding API");
2232
+ } else if ("client" in config) {
2233
+ if (!config.client) {
2234
+ throw new Error("D1 client is required when using D1ClientConfig");
2235
+ }
2236
+ this.client = config.client;
2237
+ this.logger.info("Using D1 Client");
2238
+ } else {
2239
+ if (!config.accountId || !config.databaseId || !config.apiToken) {
2240
+ throw new Error("accountId, databaseId, and apiToken are required when using REST API");
2241
+ }
2242
+ const cfClient = new Cloudflare__default.default({
2243
+ apiToken: config.apiToken
2244
+ });
2245
+ this.client = {
2246
+ query: ({ sql, params }) => {
2247
+ return cfClient.d1.database.query(config.databaseId, {
2248
+ account_id: config.accountId,
2249
+ sql,
2250
+ params
2251
+ });
2252
+ }
2253
+ };
2254
+ this.logger.info("Using D1 REST API");
2255
+ }
2256
+ } catch (error$1) {
2257
+ throw new error.MastraError(
2258
+ {
2259
+ id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
2260
+ domain: error.ErrorDomain.STORAGE,
2261
+ category: error.ErrorCategory.SYSTEM,
2262
+ text: "Error initializing D1Store"
2263
+ },
2264
+ error$1
2265
+ );
2266
+ }
2267
+ const operations = new StoreOperationsD1({
2268
+ client: this.client,
2269
+ binding: this.binding,
2270
+ tablePrefix: this.tablePrefix
2271
+ });
2272
+ const scores = new ScoresStorageD1({
2273
+ operations
2274
+ });
2275
+ const legacyEvals = new LegacyEvalsStorageD1({
2276
+ operations
2277
+ });
2278
+ const traces = new TracesStorageD1({
2279
+ operations
2280
+ });
2281
+ const workflows = new WorkflowsStorageD1({
2282
+ operations
2283
+ });
2284
+ const memory = new MemoryStorageD1({
2285
+ operations
2286
+ });
2287
+ this.stores = {
2288
+ operations,
2289
+ scores,
2290
+ legacyEvals,
2291
+ traces,
2292
+ workflows,
2293
+ memory
2294
+ };
2295
+ }
2296
+ get supports() {
2297
+ return {
2298
+ selectByIncludeResourceScope: true,
2299
+ resourceWorkingMemory: true,
2300
+ hasColumn: true,
2301
+ createTable: true,
2302
+ deleteMessages: false,
2303
+ getScoresBySpan: true
2304
+ };
2305
+ }
2306
+ async createTable({
2307
+ tableName,
2308
+ schema
2309
+ }) {
2310
+ return this.stores.operations.createTable({ tableName, schema });
2311
+ }
2312
+ /**
2313
+ * Alters table schema to add columns if they don't exist
2314
+ * @param tableName Name of the table
2315
+ * @param schema Schema of the table
2316
+ * @param ifNotExists Array of column names to add if they don't exist
2317
+ */
2318
+ async alterTable({
2319
+ tableName,
2320
+ schema,
2321
+ ifNotExists
2322
+ }) {
2323
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2324
+ }
2325
+ async clearTable({ tableName }) {
2326
+ return this.stores.operations.clearTable({ tableName });
2327
+ }
2328
+ async dropTable({ tableName }) {
2329
+ return this.stores.operations.dropTable({ tableName });
2330
+ }
2331
+ async hasColumn(table, column) {
2332
+ return this.stores.operations.hasColumn(table, column);
2333
+ }
2334
+ async insert({ tableName, record }) {
2335
+ return this.stores.operations.insert({ tableName, record });
2336
+ }
2337
+ async load({ tableName, keys }) {
2338
+ return this.stores.operations.load({ tableName, keys });
2339
+ }
2340
+ async getThreadById({ threadId }) {
2341
+ return this.stores.memory.getThreadById({ threadId });
2342
+ }
2343
+ /**
2344
+ * @deprecated use getThreadsByResourceIdPaginated instead
2345
+ */
2346
+ async getThreadsByResourceId({ resourceId }) {
2347
+ return this.stores.memory.getThreadsByResourceId({ resourceId });
2348
+ }
2349
+ async getThreadsByResourceIdPaginated(args) {
2350
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2351
+ }
2352
+ async saveThread({ thread }) {
2353
+ return this.stores.memory.saveThread({ thread });
2354
+ }
2355
+ async updateThread({
2356
+ id,
2357
+ title,
2358
+ metadata
2359
+ }) {
2360
+ return this.stores.memory.updateThread({ id, title, metadata });
2361
+ }
2362
+ async deleteThread({ threadId }) {
2363
+ return this.stores.memory.deleteThread({ threadId });
2364
+ }
2365
+ async saveMessages(args) {
2366
+ return this.stores.memory.saveMessages(args);
2367
+ }
2368
+ async getMessages({
2369
+ threadId,
2370
+ selectBy,
2371
+ format
2372
+ }) {
2373
+ return this.stores.memory.getMessages({ threadId, selectBy, format });
2374
+ }
2375
+ async getMessagesById({
2376
+ messageIds,
2377
+ format
2378
+ }) {
2379
+ return this.stores.memory.getMessagesById({ messageIds, format });
2380
+ }
2381
+ async getMessagesPaginated({
2382
+ threadId,
2383
+ selectBy,
2384
+ format
2385
+ }) {
2386
+ return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2387
+ }
2388
+ async updateWorkflowResults({
2389
+ workflowName,
2390
+ runId,
2391
+ stepId,
2392
+ result,
2393
+ runtimeContext
2394
+ }) {
2395
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2396
+ }
2397
+ async updateWorkflowState({
2398
+ workflowName,
2399
+ runId,
2400
+ opts
2401
+ }) {
2402
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2403
+ }
2404
+ async persistWorkflowSnapshot({
2405
+ workflowName,
2406
+ runId,
2407
+ resourceId,
2408
+ snapshot
2409
+ }) {
2410
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2411
+ }
2412
+ async loadWorkflowSnapshot(params) {
2413
+ return this.stores.workflows.loadWorkflowSnapshot(params);
2414
+ }
2415
+ async getWorkflowRuns({
2416
+ workflowName,
2417
+ fromDate,
2418
+ toDate,
2419
+ limit,
2420
+ offset,
2421
+ resourceId
2422
+ } = {}) {
2423
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2424
+ }
2425
+ async getWorkflowRunById({
2426
+ runId,
2427
+ workflowName
2428
+ }) {
2429
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2430
+ }
2431
+ /**
2432
+ * Insert multiple records in a batch operation
2433
+ * @param tableName The table to insert into
2434
+ * @param records The records to insert
2435
+ */
2436
+ async batchInsert({ tableName, records }) {
2437
+ return this.stores.operations.batchInsert({ tableName, records });
2438
+ }
2439
+ /**
2440
+ * @deprecated use getTracesPaginated instead
2441
+ */
2442
+ async getTraces(args) {
2443
+ return this.stores.traces.getTraces(args);
2444
+ }
2445
+ async getTracesPaginated(args) {
2446
+ return this.stores.traces.getTracesPaginated(args);
2447
+ }
2448
+ /**
2449
+ * @deprecated use getEvals instead
2450
+ */
2451
+ async getEvalsByAgentName(agentName, type) {
2452
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2453
+ }
2454
+ async getEvals(options) {
2455
+ return this.stores.legacyEvals.getEvals(options);
2456
+ }
2457
+ async updateMessages(_args) {
2458
+ return this.stores.memory.updateMessages(_args);
2459
+ }
2460
+ async getResourceById({ resourceId }) {
2461
+ return this.stores.memory.getResourceById({ resourceId });
2462
+ }
2463
+ async saveResource({ resource }) {
2464
+ return this.stores.memory.saveResource({ resource });
2465
+ }
2466
+ async updateResource({
2467
+ resourceId,
2468
+ workingMemory,
2469
+ metadata
2470
+ }) {
2471
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2472
+ }
2473
+ async getScoreById({ id: _id }) {
2474
+ return this.stores.scores.getScoreById({ id: _id });
2475
+ }
2476
+ async saveScore(_score) {
2477
+ return this.stores.scores.saveScore(_score);
2478
+ }
2479
+ async getScoresByRunId({
2480
+ runId: _runId,
2481
+ pagination: _pagination
2482
+ }) {
2483
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2484
+ }
2485
+ async getScoresByEntityId({
2486
+ entityId: _entityId,
2487
+ entityType: _entityType,
2488
+ pagination: _pagination
2489
+ }) {
2490
+ return this.stores.scores.getScoresByEntityId({
2491
+ entityId: _entityId,
2492
+ entityType: _entityType,
2493
+ pagination: _pagination
2494
+ });
2495
+ }
2496
+ async getScoresByScorerId({
2497
+ scorerId,
2498
+ pagination,
2499
+ entityId,
2500
+ entityType,
2501
+ source
2502
+ }) {
2503
+ return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2504
+ }
2505
+ async getScoresBySpan({
2506
+ traceId,
2507
+ spanId,
2508
+ pagination
2509
+ }) {
2510
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2511
+ }
1642
2512
  /**
1643
2513
  * Close the database connection
1644
2514
  * No explicit cleanup needed for D1 in either REST or Workers Binding mode
@@ -1646,10 +2516,8 @@ var D1Store = class extends storage.MastraStorage {
1646
2516
  async close() {
1647
2517
  this.logger.debug("Closing D1 connection");
1648
2518
  }
1649
- async updateMessages(_args) {
1650
- this.logger.error("updateMessages is not yet implemented in CloudflareD1Store");
1651
- throw new Error("Method not implemented");
1652
- }
1653
2519
  };
1654
2520
 
1655
2521
  exports.D1Store = D1Store;
2522
+ //# sourceMappingURL=index.cjs.map
2523
+ //# sourceMappingURL=index.cjs.map