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