@mastra/pg 0.17.8 → 1.0.0-beta.0
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 +222 -24
- package/README.md +69 -20
- package/dist/index.cjs +271 -585
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +271 -585
- package/dist/index.js.map +1 -1
- package/dist/shared/config.d.ts +1 -0
- package/dist/shared/config.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +14 -45
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts +16 -16
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/domains/operations/index.d.ts.map +1 -1
- package/dist/storage/domains/scores/index.d.ts +5 -5
- package/dist/storage/domains/scores/index.d.ts.map +1 -1
- package/dist/storage/domains/workflows/index.d.ts +4 -10
- package/dist/storage/domains/workflows/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +34 -93
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/performance-indexes/performance-test.d.ts.map +1 -1
- package/dist/storage/test-utils.d.ts.map +1 -1
- package/dist/vector/index.d.ts +3 -1
- package/dist/vector/index.d.ts.map +1 -1
- package/package.json +8 -12
- package/dist/storage/domains/legacy-evals/index.d.ts +0 -20
- package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
- package/dist/storage/domains/traces/index.d.ts +0 -23
- package/dist/storage/domains/traces/index.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -10,7 +10,7 @@ var filter = require('@mastra/core/vector/filter');
|
|
|
10
10
|
var storage = require('@mastra/core/storage');
|
|
11
11
|
var pgPromise = require('pg-promise');
|
|
12
12
|
var agent = require('@mastra/core/agent');
|
|
13
|
-
var
|
|
13
|
+
var evals = require('@mastra/core/evals');
|
|
14
14
|
|
|
15
15
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
16
16
|
|
|
@@ -49,6 +49,9 @@ var isCloudSqlConfig = (cfg) => {
|
|
|
49
49
|
return "stream" in cfg || "password" in cfg && typeof cfg.password === "function";
|
|
50
50
|
};
|
|
51
51
|
var validateConfig = (name, config) => {
|
|
52
|
+
if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
|
|
53
|
+
throw new Error(`${name}: id must be provided and cannot be empty.`);
|
|
54
|
+
}
|
|
52
55
|
if (isConnectionStringConfig(config)) {
|
|
53
56
|
if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
|
|
54
57
|
throw new Error(
|
|
@@ -429,7 +432,7 @@ var PgVector = class extends vector.MastraVector {
|
|
|
429
432
|
constructor(config) {
|
|
430
433
|
try {
|
|
431
434
|
validateConfig("PgVector", config);
|
|
432
|
-
super();
|
|
435
|
+
super({ id: config.id });
|
|
433
436
|
this.schema = config.schemaName;
|
|
434
437
|
let poolConfig;
|
|
435
438
|
if (isConnectionStringConfig(config)) {
|
|
@@ -465,14 +468,7 @@ var PgVector = class extends vector.MastraVector {
|
|
|
465
468
|
} else {
|
|
466
469
|
throw new Error("PgVector: invalid configuration provided");
|
|
467
470
|
}
|
|
468
|
-
|
|
469
|
-
const telemetry = this.__getTelemetry();
|
|
470
|
-
this.pool = telemetry?.traceClass(basePool, {
|
|
471
|
-
spanNamePrefix: "pg-vector",
|
|
472
|
-
attributes: {
|
|
473
|
-
"vector.type": "postgres"
|
|
474
|
-
}
|
|
475
|
-
}) ?? basePool;
|
|
471
|
+
this.pool = new pg__namespace.Pool(poolConfig);
|
|
476
472
|
this.cacheWarmupPromise = (async () => {
|
|
477
473
|
try {
|
|
478
474
|
const existingIndexes = await this.listIndexes();
|
|
@@ -749,7 +745,7 @@ var PgVector = class extends vector.MastraVector {
|
|
|
749
745
|
const schemaCheck = await client.query(
|
|
750
746
|
`
|
|
751
747
|
SELECT EXISTS (
|
|
752
|
-
SELECT 1 FROM information_schema.schemata
|
|
748
|
+
SELECT 1 FROM information_schema.schemata
|
|
753
749
|
WHERE schema_name = $1
|
|
754
750
|
)
|
|
755
751
|
`,
|
|
@@ -946,8 +942,8 @@ var PgVector = class extends vector.MastraVector {
|
|
|
946
942
|
const m = indexConfig.hnsw?.m ?? 8;
|
|
947
943
|
const efConstruction = indexConfig.hnsw?.efConstruction ?? 32;
|
|
948
944
|
indexSQL = `
|
|
949
|
-
CREATE INDEX IF NOT EXISTS ${vectorIndexName}
|
|
950
|
-
ON ${tableName}
|
|
945
|
+
CREATE INDEX IF NOT EXISTS ${vectorIndexName}
|
|
946
|
+
ON ${tableName}
|
|
951
947
|
USING hnsw (embedding ${metricOp})
|
|
952
948
|
WITH (
|
|
953
949
|
m = ${m},
|
|
@@ -1398,123 +1394,7 @@ function transformFromSqlRow({
|
|
|
1398
1394
|
return result;
|
|
1399
1395
|
}
|
|
1400
1396
|
|
|
1401
|
-
// src/storage/domains/
|
|
1402
|
-
function transformEvalRow(row) {
|
|
1403
|
-
let testInfoValue = null;
|
|
1404
|
-
if (row.test_info) {
|
|
1405
|
-
try {
|
|
1406
|
-
testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
|
|
1407
|
-
} catch (e) {
|
|
1408
|
-
console.warn("Failed to parse test_info:", e);
|
|
1409
|
-
}
|
|
1410
|
-
}
|
|
1411
|
-
return {
|
|
1412
|
-
agentName: row.agent_name,
|
|
1413
|
-
input: row.input,
|
|
1414
|
-
output: row.output,
|
|
1415
|
-
result: row.result,
|
|
1416
|
-
metricName: row.metric_name,
|
|
1417
|
-
instructions: row.instructions,
|
|
1418
|
-
testInfo: testInfoValue,
|
|
1419
|
-
globalRunId: row.global_run_id,
|
|
1420
|
-
runId: row.run_id,
|
|
1421
|
-
createdAt: row.created_atZ || row.created_at
|
|
1422
|
-
};
|
|
1423
|
-
}
|
|
1424
|
-
var LegacyEvalsPG = class extends storage.LegacyEvalsStorage {
|
|
1425
|
-
client;
|
|
1426
|
-
schema;
|
|
1427
|
-
constructor({ client, schema }) {
|
|
1428
|
-
super();
|
|
1429
|
-
this.client = client;
|
|
1430
|
-
this.schema = schema;
|
|
1431
|
-
}
|
|
1432
|
-
/** @deprecated use getEvals instead */
|
|
1433
|
-
async getEvalsByAgentName(agentName, type) {
|
|
1434
|
-
try {
|
|
1435
|
-
const baseQuery = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = $1`;
|
|
1436
|
-
const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
|
|
1437
|
-
const query = `${baseQuery}${typeCondition} ORDER BY created_at DESC`;
|
|
1438
|
-
const rows = await this.client.manyOrNone(query, [agentName]);
|
|
1439
|
-
return rows?.map((row) => transformEvalRow(row)) ?? [];
|
|
1440
|
-
} catch (error) {
|
|
1441
|
-
if (error instanceof Error && error.message.includes("relation") && error.message.includes("does not exist")) {
|
|
1442
|
-
return [];
|
|
1443
|
-
}
|
|
1444
|
-
console.error("Failed to get evals for the specified agent: " + error?.message);
|
|
1445
|
-
throw error;
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
async getEvals(options = {}) {
|
|
1449
|
-
const tableName = getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) });
|
|
1450
|
-
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
1451
|
-
const fromDate = dateRange?.start;
|
|
1452
|
-
const toDate = dateRange?.end;
|
|
1453
|
-
const conditions = [];
|
|
1454
|
-
const queryParams = [];
|
|
1455
|
-
let paramIndex = 1;
|
|
1456
|
-
if (agentName) {
|
|
1457
|
-
conditions.push(`agent_name = $${paramIndex++}`);
|
|
1458
|
-
queryParams.push(agentName);
|
|
1459
|
-
}
|
|
1460
|
-
if (type === "test") {
|
|
1461
|
-
conditions.push(`(test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL)`);
|
|
1462
|
-
} else if (type === "live") {
|
|
1463
|
-
conditions.push(`(test_info IS NULL OR test_info->>'testPath' IS NULL)`);
|
|
1464
|
-
}
|
|
1465
|
-
if (fromDate) {
|
|
1466
|
-
conditions.push(`created_at >= $${paramIndex++}`);
|
|
1467
|
-
queryParams.push(fromDate);
|
|
1468
|
-
}
|
|
1469
|
-
if (toDate) {
|
|
1470
|
-
conditions.push(`created_at <= $${paramIndex++}`);
|
|
1471
|
-
queryParams.push(toDate);
|
|
1472
|
-
}
|
|
1473
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1474
|
-
const countQuery = `SELECT COUNT(*) FROM ${tableName} ${whereClause}`;
|
|
1475
|
-
try {
|
|
1476
|
-
const countResult = await this.client.one(countQuery, queryParams);
|
|
1477
|
-
const total = parseInt(countResult.count, 10);
|
|
1478
|
-
const currentOffset = page * perPage;
|
|
1479
|
-
if (total === 0) {
|
|
1480
|
-
return {
|
|
1481
|
-
evals: [],
|
|
1482
|
-
total: 0,
|
|
1483
|
-
page,
|
|
1484
|
-
perPage,
|
|
1485
|
-
hasMore: false
|
|
1486
|
-
};
|
|
1487
|
-
}
|
|
1488
|
-
const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY created_at DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
|
|
1489
|
-
const rows = await this.client.manyOrNone(dataQuery, [...queryParams, perPage, currentOffset]);
|
|
1490
|
-
return {
|
|
1491
|
-
evals: rows?.map((row) => transformEvalRow(row)) ?? [],
|
|
1492
|
-
total,
|
|
1493
|
-
page,
|
|
1494
|
-
perPage,
|
|
1495
|
-
hasMore: currentOffset + (rows?.length ?? 0) < total
|
|
1496
|
-
};
|
|
1497
|
-
} catch (error$1) {
|
|
1498
|
-
const mastraError = new error.MastraError(
|
|
1499
|
-
{
|
|
1500
|
-
id: "MASTRA_STORAGE_PG_STORE_GET_EVALS_FAILED",
|
|
1501
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1502
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1503
|
-
details: {
|
|
1504
|
-
agentName: agentName || "all",
|
|
1505
|
-
type: type || "all",
|
|
1506
|
-
page,
|
|
1507
|
-
perPage
|
|
1508
|
-
}
|
|
1509
|
-
},
|
|
1510
|
-
error$1
|
|
1511
|
-
);
|
|
1512
|
-
this.logger?.error?.(mastraError.toString());
|
|
1513
|
-
this.logger?.trackException(mastraError);
|
|
1514
|
-
throw mastraError;
|
|
1515
|
-
}
|
|
1516
|
-
}
|
|
1517
|
-
};
|
|
1397
|
+
// src/storage/domains/memory/index.ts
|
|
1518
1398
|
var MemoryPG = class extends storage.MemoryStorage {
|
|
1519
1399
|
client;
|
|
1520
1400
|
schema;
|
|
@@ -1575,40 +1455,27 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1575
1455
|
);
|
|
1576
1456
|
}
|
|
1577
1457
|
}
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
return (rows || []).map((thread) => ({
|
|
1592
|
-
...thread,
|
|
1593
|
-
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
1594
|
-
createdAt: thread.createdAt,
|
|
1595
|
-
updatedAt: thread.updatedAt
|
|
1596
|
-
}));
|
|
1597
|
-
} catch (error) {
|
|
1598
|
-
this.logger.error(`Error getting threads for resource ${resourceId}:`, error);
|
|
1599
|
-
return [];
|
|
1458
|
+
async listThreadsByResourceId(args) {
|
|
1459
|
+
const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
|
|
1460
|
+
if (page < 0) {
|
|
1461
|
+
throw new error.MastraError({
|
|
1462
|
+
id: "MASTRA_STORAGE_PG_STORE_INVALID_PAGE",
|
|
1463
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1464
|
+
category: error.ErrorCategory.USER,
|
|
1465
|
+
text: "Page number must be non-negative",
|
|
1466
|
+
details: {
|
|
1467
|
+
resourceId,
|
|
1468
|
+
page
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1600
1471
|
}
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
const {
|
|
1604
|
-
const orderBy = this.castThreadOrderBy(args.orderBy);
|
|
1605
|
-
const sortDirection = this.castThreadSortDirection(args.sortDirection);
|
|
1472
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
1473
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
1474
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1606
1475
|
try {
|
|
1607
1476
|
const tableName = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
|
|
1608
1477
|
const baseQuery = `FROM ${tableName} WHERE "resourceId" = $1`;
|
|
1609
1478
|
const queryParams = [resourceId];
|
|
1610
|
-
const perPage = perPageInput !== void 0 ? perPageInput : 100;
|
|
1611
|
-
const currentOffset = page * perPage;
|
|
1612
1479
|
const countQuery = `SELECT COUNT(*) ${baseQuery}`;
|
|
1613
1480
|
const countResult = await this.client.one(countQuery, queryParams);
|
|
1614
1481
|
const total = parseInt(countResult.count, 10);
|
|
@@ -1617,12 +1484,13 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1617
1484
|
threads: [],
|
|
1618
1485
|
total: 0,
|
|
1619
1486
|
page,
|
|
1620
|
-
perPage,
|
|
1487
|
+
perPage: perPageForResponse,
|
|
1621
1488
|
hasMore: false
|
|
1622
1489
|
};
|
|
1623
1490
|
}
|
|
1624
|
-
const
|
|
1625
|
-
const
|
|
1491
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1492
|
+
const dataQuery = `SELECT id, "resourceId", title, metadata, "createdAt", "updatedAt" ${baseQuery} ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`;
|
|
1493
|
+
const rows = await this.client.manyOrNone(dataQuery, [...queryParams, limitValue, offset]);
|
|
1626
1494
|
const threads = (rows || []).map((thread) => ({
|
|
1627
1495
|
...thread,
|
|
1628
1496
|
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
@@ -1634,13 +1502,13 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1634
1502
|
threads,
|
|
1635
1503
|
total,
|
|
1636
1504
|
page,
|
|
1637
|
-
perPage,
|
|
1638
|
-
hasMore:
|
|
1505
|
+
perPage: perPageForResponse,
|
|
1506
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
1639
1507
|
};
|
|
1640
1508
|
} catch (error$1) {
|
|
1641
1509
|
const mastraError = new error.MastraError(
|
|
1642
1510
|
{
|
|
1643
|
-
id: "
|
|
1511
|
+
id: "MASTRA_STORAGE_PG_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
|
|
1644
1512
|
domain: error.ErrorDomain.STORAGE,
|
|
1645
1513
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1646
1514
|
details: {
|
|
@@ -1652,7 +1520,13 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1652
1520
|
);
|
|
1653
1521
|
this.logger?.error?.(mastraError.toString());
|
|
1654
1522
|
this.logger?.trackException(mastraError);
|
|
1655
|
-
return {
|
|
1523
|
+
return {
|
|
1524
|
+
threads: [],
|
|
1525
|
+
total: 0,
|
|
1526
|
+
page,
|
|
1527
|
+
perPage: perPageForResponse,
|
|
1528
|
+
hasMore: false
|
|
1529
|
+
};
|
|
1656
1530
|
}
|
|
1657
1531
|
}
|
|
1658
1532
|
async saveThread({ thread }) {
|
|
@@ -1786,11 +1660,9 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1786
1660
|
}
|
|
1787
1661
|
async _getIncludedMessages({
|
|
1788
1662
|
threadId,
|
|
1789
|
-
|
|
1790
|
-
orderByStatement
|
|
1663
|
+
include
|
|
1791
1664
|
}) {
|
|
1792
1665
|
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1793
|
-
const include = selectBy?.include;
|
|
1794
1666
|
if (!include) return null;
|
|
1795
1667
|
const unionQueries = [];
|
|
1796
1668
|
const params = [];
|
|
@@ -1805,7 +1677,7 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1805
1677
|
WITH ordered_messages AS (
|
|
1806
1678
|
SELECT
|
|
1807
1679
|
*,
|
|
1808
|
-
ROW_NUMBER() OVER (
|
|
1680
|
+
ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
|
|
1809
1681
|
FROM ${tableName}
|
|
1810
1682
|
WHERE thread_id = $${paramIdx}
|
|
1811
1683
|
)
|
|
@@ -1824,11 +1696,11 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1824
1696
|
SELECT 1 FROM ordered_messages target
|
|
1825
1697
|
WHERE target.id = $${paramIdx + 1}
|
|
1826
1698
|
AND (
|
|
1827
|
-
-- Get previous messages
|
|
1828
|
-
(m.row_num
|
|
1699
|
+
-- Get previous messages (messages that come BEFORE the target)
|
|
1700
|
+
(m.row_num < target.row_num AND m.row_num >= target.row_num - $${paramIdx + 2})
|
|
1829
1701
|
OR
|
|
1830
|
-
-- Get next messages
|
|
1831
|
-
(m.row_num
|
|
1702
|
+
-- Get next messages (messages that come AFTER the target)
|
|
1703
|
+
(m.row_num > target.row_num AND m.row_num <= target.row_num + $${paramIdx + 3})
|
|
1832
1704
|
)
|
|
1833
1705
|
)
|
|
1834
1706
|
) AS query_${paramIdx}
|
|
@@ -1865,72 +1737,8 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1865
1737
|
...normalized.type && normalized.type !== "v2" ? { type: normalized.type } : {}
|
|
1866
1738
|
};
|
|
1867
1739
|
}
|
|
1868
|
-
async
|
|
1869
|
-
|
|
1870
|
-
const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
|
|
1871
|
-
const orderByStatement = `ORDER BY "createdAt" DESC`;
|
|
1872
|
-
const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
1873
|
-
try {
|
|
1874
|
-
if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
|
|
1875
|
-
let rows = [];
|
|
1876
|
-
const include = selectBy?.include || [];
|
|
1877
|
-
if (include?.length) {
|
|
1878
|
-
const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
|
|
1879
|
-
if (includeMessages) {
|
|
1880
|
-
rows.push(...includeMessages);
|
|
1881
|
-
}
|
|
1882
|
-
}
|
|
1883
|
-
const excludeIds = rows.map((m) => m.id);
|
|
1884
|
-
const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
1885
|
-
const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + 2}`).join(", ");
|
|
1886
|
-
let query = `${selectStatement} FROM ${tableName} WHERE thread_id = $1
|
|
1887
|
-
${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""}
|
|
1888
|
-
${orderByStatement}
|
|
1889
|
-
LIMIT $${excludeIds.length + 2}
|
|
1890
|
-
`;
|
|
1891
|
-
const queryParams = [threadId, ...excludeIds, limit];
|
|
1892
|
-
const remainingRows = await this.client.manyOrNone(query, queryParams);
|
|
1893
|
-
rows.push(...remainingRows);
|
|
1894
|
-
const fetchedMessages = (rows || []).map((row) => {
|
|
1895
|
-
const message = this.normalizeMessageRow(row);
|
|
1896
|
-
if (typeof message.content === "string") {
|
|
1897
|
-
try {
|
|
1898
|
-
message.content = JSON.parse(message.content);
|
|
1899
|
-
} catch {
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
if (message.type === "v2") delete message.type;
|
|
1903
|
-
return message;
|
|
1904
|
-
});
|
|
1905
|
-
const sortedMessages = fetchedMessages.sort(
|
|
1906
|
-
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
|
|
1907
|
-
);
|
|
1908
|
-
return format === "v2" ? sortedMessages.map(
|
|
1909
|
-
(m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
|
|
1910
|
-
) : sortedMessages;
|
|
1911
|
-
} catch (error$1) {
|
|
1912
|
-
const mastraError = new error.MastraError(
|
|
1913
|
-
{
|
|
1914
|
-
id: "MASTRA_STORAGE_PG_STORE_GET_MESSAGES_FAILED",
|
|
1915
|
-
domain: error.ErrorDomain.STORAGE,
|
|
1916
|
-
category: error.ErrorCategory.THIRD_PARTY,
|
|
1917
|
-
details: {
|
|
1918
|
-
threadId,
|
|
1919
|
-
resourceId: resourceId ?? ""
|
|
1920
|
-
}
|
|
1921
|
-
},
|
|
1922
|
-
error$1
|
|
1923
|
-
);
|
|
1924
|
-
this.logger?.error?.(mastraError.toString());
|
|
1925
|
-
this.logger?.trackException(mastraError);
|
|
1926
|
-
return [];
|
|
1927
|
-
}
|
|
1928
|
-
}
|
|
1929
|
-
async getMessagesById({
|
|
1930
|
-
messageIds,
|
|
1931
|
-
format
|
|
1932
|
-
}) {
|
|
1933
|
-
if (messageIds.length === 0) return [];
|
|
1740
|
+
async listMessagesById({ messageIds }) {
|
|
1741
|
+
if (messageIds.length === 0) return { messages: [] };
|
|
1934
1742
|
const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
|
|
1935
1743
|
try {
|
|
1936
1744
|
const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
@@ -1944,12 +1752,11 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1944
1752
|
resultRows.map((row) => this.parseRow(row)),
|
|
1945
1753
|
"memory"
|
|
1946
1754
|
);
|
|
1947
|
-
|
|
1948
|
-
return list.get.all.v2();
|
|
1755
|
+
return { messages: list.get.all.db() };
|
|
1949
1756
|
} catch (error$1) {
|
|
1950
1757
|
const mastraError = new error.MastraError(
|
|
1951
1758
|
{
|
|
1952
|
-
id: "
|
|
1759
|
+
id: "MASTRA_STORAGE_PG_STORE_LIST_MESSAGES_BY_ID_FAILED",
|
|
1953
1760
|
domain: error.ErrorDomain.STORAGE,
|
|
1954
1761
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
1955
1762
|
details: {
|
|
@@ -1960,102 +1767,138 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
1960
1767
|
);
|
|
1961
1768
|
this.logger?.error?.(mastraError.toString());
|
|
1962
1769
|
this.logger?.trackException(mastraError);
|
|
1963
|
-
return [];
|
|
1770
|
+
return { messages: [] };
|
|
1964
1771
|
}
|
|
1965
1772
|
}
|
|
1966
|
-
async
|
|
1967
|
-
const { threadId, resourceId,
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1773
|
+
async listMessages(args) {
|
|
1774
|
+
const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
|
|
1775
|
+
if (!threadId.trim()) {
|
|
1776
|
+
throw new error.MastraError(
|
|
1777
|
+
{
|
|
1778
|
+
id: "STORAGE_PG_LIST_MESSAGES_INVALID_THREAD_ID",
|
|
1779
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1780
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1781
|
+
details: { threadId }
|
|
1782
|
+
},
|
|
1783
|
+
new Error("threadId must be a non-empty string")
|
|
1784
|
+
);
|
|
1785
|
+
}
|
|
1786
|
+
if (page < 0) {
|
|
1787
|
+
throw new error.MastraError({
|
|
1788
|
+
id: "MASTRA_STORAGE_PG_STORE_INVALID_PAGE",
|
|
1789
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1790
|
+
category: error.ErrorCategory.USER,
|
|
1791
|
+
text: "Page number must be non-negative",
|
|
1792
|
+
details: {
|
|
1793
|
+
threadId,
|
|
1794
|
+
page
|
|
1980
1795
|
}
|
|
1981
|
-
}
|
|
1982
|
-
|
|
1983
|
-
|
|
1796
|
+
});
|
|
1797
|
+
}
|
|
1798
|
+
const perPage = storage.normalizePerPage(perPageInput, 40);
|
|
1799
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
1800
|
+
try {
|
|
1801
|
+
const { field, direction } = this.parseOrderBy(orderBy, "ASC");
|
|
1802
|
+
const orderByStatement = `ORDER BY "${field}" ${direction}`;
|
|
1803
|
+
const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
|
|
1804
|
+
const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
1984
1805
|
const conditions = [`thread_id = $1`];
|
|
1985
1806
|
const queryParams = [threadId];
|
|
1986
1807
|
let paramIndex = 2;
|
|
1987
|
-
if (
|
|
1808
|
+
if (resourceId) {
|
|
1809
|
+
conditions.push(`"resourceId" = $${paramIndex++}`);
|
|
1810
|
+
queryParams.push(resourceId);
|
|
1811
|
+
}
|
|
1812
|
+
if (filter?.dateRange?.start) {
|
|
1988
1813
|
conditions.push(`"createdAt" >= $${paramIndex++}`);
|
|
1989
|
-
queryParams.push(
|
|
1814
|
+
queryParams.push(filter.dateRange.start);
|
|
1990
1815
|
}
|
|
1991
|
-
if (
|
|
1816
|
+
if (filter?.dateRange?.end) {
|
|
1992
1817
|
conditions.push(`"createdAt" <= $${paramIndex++}`);
|
|
1993
|
-
queryParams.push(
|
|
1818
|
+
queryParams.push(filter.dateRange.end);
|
|
1994
1819
|
}
|
|
1995
1820
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1996
|
-
const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
|
|
1997
1821
|
const countQuery = `SELECT COUNT(*) FROM ${tableName} ${whereClause}`;
|
|
1998
1822
|
const countResult = await this.client.one(countQuery, queryParams);
|
|
1999
1823
|
const total = parseInt(countResult.count, 10);
|
|
2000
|
-
|
|
1824
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
1825
|
+
const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
|
|
1826
|
+
const rows = await this.client.manyOrNone(dataQuery, [...queryParams, limitValue, offset]);
|
|
1827
|
+
const messages = [...rows || []];
|
|
1828
|
+
if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
|
|
2001
1829
|
return {
|
|
2002
1830
|
messages: [],
|
|
2003
1831
|
total: 0,
|
|
2004
1832
|
page,
|
|
2005
|
-
perPage,
|
|
1833
|
+
perPage: perPageForResponse,
|
|
2006
1834
|
hasMore: false
|
|
2007
1835
|
};
|
|
2008
1836
|
}
|
|
2009
|
-
const
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
try {
|
|
2019
|
-
return { ...message, content: JSON.parse(message.content) };
|
|
2020
|
-
} catch {
|
|
2021
|
-
return message;
|
|
1837
|
+
const messageIds = new Set(messages.map((m) => m.id));
|
|
1838
|
+
if (include && include.length > 0) {
|
|
1839
|
+
const includeMessages = await this._getIncludedMessages({ threadId, include });
|
|
1840
|
+
if (includeMessages) {
|
|
1841
|
+
for (const includeMsg of includeMessages) {
|
|
1842
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
1843
|
+
messages.push(includeMsg);
|
|
1844
|
+
messageIds.add(includeMsg.id);
|
|
1845
|
+
}
|
|
2022
1846
|
}
|
|
2023
1847
|
}
|
|
2024
|
-
|
|
2025
|
-
|
|
1848
|
+
}
|
|
1849
|
+
const messagesWithParsedContent = messages.map((row) => this.parseRow(row));
|
|
2026
1850
|
const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
|
|
2027
|
-
|
|
1851
|
+
let finalMessages = list.get.all.db();
|
|
1852
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
1853
|
+
const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
|
|
1854
|
+
const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
|
|
1855
|
+
if (aValue == null && bValue == null) return a.id.localeCompare(b.id);
|
|
1856
|
+
if (aValue == null) return 1;
|
|
1857
|
+
if (bValue == null) return -1;
|
|
1858
|
+
if (aValue === bValue) {
|
|
1859
|
+
return a.id.localeCompare(b.id);
|
|
1860
|
+
}
|
|
1861
|
+
if (typeof aValue === "number" && typeof bValue === "number") {
|
|
1862
|
+
return direction === "ASC" ? aValue - bValue : bValue - aValue;
|
|
1863
|
+
}
|
|
1864
|
+
return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
|
|
1865
|
+
});
|
|
1866
|
+
const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
|
|
1867
|
+
const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
|
|
1868
|
+
const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
|
|
2028
1869
|
return {
|
|
2029
|
-
messages:
|
|
1870
|
+
messages: finalMessages,
|
|
2030
1871
|
total,
|
|
2031
1872
|
page,
|
|
2032
|
-
perPage,
|
|
2033
|
-
hasMore
|
|
1873
|
+
perPage: perPageForResponse,
|
|
1874
|
+
hasMore
|
|
2034
1875
|
};
|
|
2035
1876
|
} catch (error$1) {
|
|
2036
1877
|
const mastraError = new error.MastraError(
|
|
2037
1878
|
{
|
|
2038
|
-
id: "
|
|
1879
|
+
id: "MASTRA_STORAGE_PG_STORE_LIST_MESSAGES_FAILED",
|
|
2039
1880
|
domain: error.ErrorDomain.STORAGE,
|
|
2040
1881
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
2041
1882
|
details: {
|
|
2042
1883
|
threadId,
|
|
2043
|
-
resourceId: resourceId ?? ""
|
|
2044
|
-
page
|
|
1884
|
+
resourceId: resourceId ?? ""
|
|
2045
1885
|
}
|
|
2046
1886
|
},
|
|
2047
1887
|
error$1
|
|
2048
1888
|
);
|
|
2049
1889
|
this.logger?.error?.(mastraError.toString());
|
|
2050
1890
|
this.logger?.trackException(mastraError);
|
|
2051
|
-
return {
|
|
1891
|
+
return {
|
|
1892
|
+
messages: [],
|
|
1893
|
+
total: 0,
|
|
1894
|
+
page,
|
|
1895
|
+
perPage: perPageForResponse,
|
|
1896
|
+
hasMore: false
|
|
1897
|
+
};
|
|
2052
1898
|
}
|
|
2053
1899
|
}
|
|
2054
|
-
async saveMessages({
|
|
2055
|
-
messages
|
|
2056
|
-
format
|
|
2057
|
-
}) {
|
|
2058
|
-
if (messages.length === 0) return messages;
|
|
1900
|
+
async saveMessages({ messages }) {
|
|
1901
|
+
if (messages.length === 0) return { messages: [] };
|
|
2059
1902
|
const threadId = messages[0]?.threadId;
|
|
2060
1903
|
if (!threadId) {
|
|
2061
1904
|
throw new error.MastraError({
|
|
@@ -2135,8 +1978,7 @@ var MemoryPG = class extends storage.MemoryStorage {
|
|
|
2135
1978
|
return message;
|
|
2136
1979
|
});
|
|
2137
1980
|
const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
|
|
2138
|
-
|
|
2139
|
-
return list.get.all.v1();
|
|
1981
|
+
return { messages: list.get.all.db() };
|
|
2140
1982
|
} catch (error$1) {
|
|
2141
1983
|
throw new error.MastraError(
|
|
2142
1984
|
{
|
|
@@ -2368,13 +2210,13 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2368
2210
|
this.operations = operations;
|
|
2369
2211
|
this.schema = schema;
|
|
2370
2212
|
}
|
|
2371
|
-
get
|
|
2213
|
+
get tracingStrategy() {
|
|
2372
2214
|
return {
|
|
2373
2215
|
preferred: "batch-with-updates",
|
|
2374
2216
|
supported: ["batch-with-updates", "insert-only"]
|
|
2375
2217
|
};
|
|
2376
2218
|
}
|
|
2377
|
-
async
|
|
2219
|
+
async createSpan(span) {
|
|
2378
2220
|
try {
|
|
2379
2221
|
const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
|
|
2380
2222
|
const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
|
|
@@ -2386,11 +2228,11 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2386
2228
|
endedAtZ: endedAt
|
|
2387
2229
|
// Note: createdAt/updatedAt will be set by database triggers
|
|
2388
2230
|
};
|
|
2389
|
-
return this.operations.insert({ tableName: storage.
|
|
2231
|
+
return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
|
|
2390
2232
|
} catch (error$1) {
|
|
2391
2233
|
throw new error.MastraError(
|
|
2392
2234
|
{
|
|
2393
|
-
id: "
|
|
2235
|
+
id: "PG_STORE_CREATE_SPAN_FAILED",
|
|
2394
2236
|
domain: error.ErrorDomain.STORAGE,
|
|
2395
2237
|
category: error.ErrorCategory.USER,
|
|
2396
2238
|
details: {
|
|
@@ -2404,10 +2246,10 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2404
2246
|
);
|
|
2405
2247
|
}
|
|
2406
2248
|
}
|
|
2407
|
-
async
|
|
2249
|
+
async getTrace(traceId) {
|
|
2408
2250
|
try {
|
|
2409
2251
|
const tableName = getTableName({
|
|
2410
|
-
indexName: storage.
|
|
2252
|
+
indexName: storage.TABLE_SPANS,
|
|
2411
2253
|
schemaName: getSchemaName(this.schema)
|
|
2412
2254
|
});
|
|
2413
2255
|
const spans = await this.client.manyOrNone(
|
|
@@ -2428,7 +2270,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2428
2270
|
traceId,
|
|
2429
2271
|
spans: spans.map(
|
|
2430
2272
|
(span) => transformFromSqlRow({
|
|
2431
|
-
tableName: storage.
|
|
2273
|
+
tableName: storage.TABLE_SPANS,
|
|
2432
2274
|
sqlRow: span
|
|
2433
2275
|
})
|
|
2434
2276
|
)
|
|
@@ -2436,7 +2278,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2436
2278
|
} catch (error$1) {
|
|
2437
2279
|
throw new error.MastraError(
|
|
2438
2280
|
{
|
|
2439
|
-
id: "
|
|
2281
|
+
id: "PG_STORE_GET_TRACE_FAILED",
|
|
2440
2282
|
domain: error.ErrorDomain.STORAGE,
|
|
2441
2283
|
category: error.ErrorCategory.USER,
|
|
2442
2284
|
details: {
|
|
@@ -2447,7 +2289,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2447
2289
|
);
|
|
2448
2290
|
}
|
|
2449
2291
|
}
|
|
2450
|
-
async
|
|
2292
|
+
async updateSpan({
|
|
2451
2293
|
spanId,
|
|
2452
2294
|
traceId,
|
|
2453
2295
|
updates
|
|
@@ -2461,14 +2303,14 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2461
2303
|
data.startedAt = data.startedAt.toISOString();
|
|
2462
2304
|
}
|
|
2463
2305
|
await this.operations.update({
|
|
2464
|
-
tableName: storage.
|
|
2306
|
+
tableName: storage.TABLE_SPANS,
|
|
2465
2307
|
keys: { spanId, traceId },
|
|
2466
2308
|
data
|
|
2467
2309
|
});
|
|
2468
2310
|
} catch (error$1) {
|
|
2469
2311
|
throw new error.MastraError(
|
|
2470
2312
|
{
|
|
2471
|
-
id: "
|
|
2313
|
+
id: "PG_STORE_UPDATE_SPAN_FAILED",
|
|
2472
2314
|
domain: error.ErrorDomain.STORAGE,
|
|
2473
2315
|
category: error.ErrorCategory.USER,
|
|
2474
2316
|
details: {
|
|
@@ -2480,7 +2322,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2480
2322
|
);
|
|
2481
2323
|
}
|
|
2482
2324
|
}
|
|
2483
|
-
async
|
|
2325
|
+
async getTracesPaginated({
|
|
2484
2326
|
filters,
|
|
2485
2327
|
pagination
|
|
2486
2328
|
}) {
|
|
@@ -2504,7 +2346,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2504
2346
|
name = `agent run: '${entityId}'`;
|
|
2505
2347
|
} else {
|
|
2506
2348
|
const error$1 = new error.MastraError({
|
|
2507
|
-
id: "
|
|
2349
|
+
id: "PG_STORE_GET_TRACES_PAGINATED_FAILED",
|
|
2508
2350
|
domain: error.ErrorDomain.STORAGE,
|
|
2509
2351
|
category: error.ErrorCategory.USER,
|
|
2510
2352
|
details: {
|
|
@@ -2524,7 +2366,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2524
2366
|
}
|
|
2525
2367
|
}
|
|
2526
2368
|
const tableName = getTableName({
|
|
2527
|
-
indexName: storage.
|
|
2369
|
+
indexName: storage.TABLE_SPANS,
|
|
2528
2370
|
schemaName: getSchemaName(this.schema)
|
|
2529
2371
|
});
|
|
2530
2372
|
try {
|
|
@@ -2564,7 +2406,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2564
2406
|
},
|
|
2565
2407
|
spans: spans.map(
|
|
2566
2408
|
(span) => transformFromSqlRow({
|
|
2567
|
-
tableName: storage.
|
|
2409
|
+
tableName: storage.TABLE_SPANS,
|
|
2568
2410
|
sqlRow: span
|
|
2569
2411
|
})
|
|
2570
2412
|
)
|
|
@@ -2572,7 +2414,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2572
2414
|
} catch (error$1) {
|
|
2573
2415
|
throw new error.MastraError(
|
|
2574
2416
|
{
|
|
2575
|
-
id: "
|
|
2417
|
+
id: "PG_STORE_GET_TRACES_PAGINATED_FAILED",
|
|
2576
2418
|
domain: error.ErrorDomain.STORAGE,
|
|
2577
2419
|
category: error.ErrorCategory.USER
|
|
2578
2420
|
},
|
|
@@ -2580,7 +2422,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2580
2422
|
);
|
|
2581
2423
|
}
|
|
2582
2424
|
}
|
|
2583
|
-
async
|
|
2425
|
+
async batchCreateSpans(args) {
|
|
2584
2426
|
try {
|
|
2585
2427
|
const records = args.records.map((record) => {
|
|
2586
2428
|
const startedAt = record.startedAt instanceof Date ? record.startedAt.toISOString() : record.startedAt;
|
|
@@ -2595,13 +2437,13 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2595
2437
|
};
|
|
2596
2438
|
});
|
|
2597
2439
|
return this.operations.batchInsert({
|
|
2598
|
-
tableName: storage.
|
|
2440
|
+
tableName: storage.TABLE_SPANS,
|
|
2599
2441
|
records
|
|
2600
2442
|
});
|
|
2601
2443
|
} catch (error$1) {
|
|
2602
2444
|
throw new error.MastraError(
|
|
2603
2445
|
{
|
|
2604
|
-
id: "
|
|
2446
|
+
id: "PG_STORE_BATCH_CREATE_SPANS_FAILED",
|
|
2605
2447
|
domain: error.ErrorDomain.STORAGE,
|
|
2606
2448
|
category: error.ErrorCategory.USER
|
|
2607
2449
|
},
|
|
@@ -2609,10 +2451,10 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2609
2451
|
);
|
|
2610
2452
|
}
|
|
2611
2453
|
}
|
|
2612
|
-
async
|
|
2454
|
+
async batchUpdateSpans(args) {
|
|
2613
2455
|
try {
|
|
2614
2456
|
return this.operations.batchUpdate({
|
|
2615
|
-
tableName: storage.
|
|
2457
|
+
tableName: storage.TABLE_SPANS,
|
|
2616
2458
|
updates: args.records.map((record) => {
|
|
2617
2459
|
const data = {
|
|
2618
2460
|
...record.updates
|
|
@@ -2636,7 +2478,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2636
2478
|
} catch (error$1) {
|
|
2637
2479
|
throw new error.MastraError(
|
|
2638
2480
|
{
|
|
2639
|
-
id: "
|
|
2481
|
+
id: "PG_STORE_BATCH_UPDATE_SPANS_FAILED",
|
|
2640
2482
|
domain: error.ErrorDomain.STORAGE,
|
|
2641
2483
|
category: error.ErrorCategory.USER
|
|
2642
2484
|
},
|
|
@@ -2644,10 +2486,10 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2644
2486
|
);
|
|
2645
2487
|
}
|
|
2646
2488
|
}
|
|
2647
|
-
async
|
|
2489
|
+
async batchDeleteTraces(args) {
|
|
2648
2490
|
try {
|
|
2649
2491
|
const tableName = getTableName({
|
|
2650
|
-
indexName: storage.
|
|
2492
|
+
indexName: storage.TABLE_SPANS,
|
|
2651
2493
|
schemaName: getSchemaName(this.schema)
|
|
2652
2494
|
});
|
|
2653
2495
|
const placeholders = args.traceIds.map((_, i) => `$${i + 1}`).join(", ");
|
|
@@ -2655,7 +2497,7 @@ var ObservabilityPG = class extends storage.ObservabilityStorage {
|
|
|
2655
2497
|
} catch (error$1) {
|
|
2656
2498
|
throw new error.MastraError(
|
|
2657
2499
|
{
|
|
2658
|
-
id: "
|
|
2500
|
+
id: "PG_STORE_BATCH_DELETE_TRACES_FAILED",
|
|
2659
2501
|
domain: error.ErrorDomain.STORAGE,
|
|
2660
2502
|
category: error.ErrorCategory.USER
|
|
2661
2503
|
},
|
|
@@ -2871,7 +2713,7 @@ var StoreOperationsPG = class extends storage.StoreOperations {
|
|
|
2871
2713
|
schema,
|
|
2872
2714
|
ifNotExists: timeZColumnNames
|
|
2873
2715
|
});
|
|
2874
|
-
if (tableName === storage.
|
|
2716
|
+
if (tableName === storage.TABLE_SPANS) {
|
|
2875
2717
|
await this.setupTimestampTriggers(tableName);
|
|
2876
2718
|
}
|
|
2877
2719
|
} catch (error$1) {
|
|
@@ -3257,37 +3099,31 @@ var StoreOperationsPG = class extends storage.StoreOperations {
|
|
|
3257
3099
|
table: storage.TABLE_TRACES,
|
|
3258
3100
|
columns: ["name", "startTime DESC"]
|
|
3259
3101
|
},
|
|
3260
|
-
// Composite index for evals (filter + sort)
|
|
3261
|
-
{
|
|
3262
|
-
name: `${schemaPrefix}mastra_evals_agent_name_created_at_idx`,
|
|
3263
|
-
table: storage.TABLE_EVALS,
|
|
3264
|
-
columns: ["agent_name", "created_at DESC"]
|
|
3265
|
-
},
|
|
3266
3102
|
// Composite index for scores (filter + sort)
|
|
3267
3103
|
{
|
|
3268
3104
|
name: `${schemaPrefix}mastra_scores_trace_id_span_id_created_at_idx`,
|
|
3269
3105
|
table: storage.TABLE_SCORERS,
|
|
3270
3106
|
columns: ["traceId", "spanId", "createdAt DESC"]
|
|
3271
3107
|
},
|
|
3272
|
-
//
|
|
3108
|
+
// Spans indexes for optimal trace querying
|
|
3273
3109
|
{
|
|
3274
3110
|
name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
|
|
3275
|
-
table: storage.
|
|
3111
|
+
table: storage.TABLE_SPANS,
|
|
3276
3112
|
columns: ["traceId", "startedAt DESC"]
|
|
3277
3113
|
},
|
|
3278
3114
|
{
|
|
3279
3115
|
name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
|
|
3280
|
-
table: storage.
|
|
3116
|
+
table: storage.TABLE_SPANS,
|
|
3281
3117
|
columns: ["parentSpanId", "startedAt DESC"]
|
|
3282
3118
|
},
|
|
3283
3119
|
{
|
|
3284
3120
|
name: `${schemaPrefix}mastra_ai_spans_name_idx`,
|
|
3285
|
-
table: storage.
|
|
3121
|
+
table: storage.TABLE_SPANS,
|
|
3286
3122
|
columns: ["name"]
|
|
3287
3123
|
},
|
|
3288
3124
|
{
|
|
3289
3125
|
name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
|
|
3290
|
-
table: storage.
|
|
3126
|
+
table: storage.TABLE_SPANS,
|
|
3291
3127
|
columns: ["spanType", "startedAt DESC"]
|
|
3292
3128
|
}
|
|
3293
3129
|
];
|
|
@@ -3508,7 +3344,7 @@ function transformScoreRow(row) {
|
|
|
3508
3344
|
metadata: storage.safelyParseJSON(row.metadata),
|
|
3509
3345
|
output: storage.safelyParseJSON(row.output),
|
|
3510
3346
|
additionalContext: storage.safelyParseJSON(row.additionalContext),
|
|
3511
|
-
|
|
3347
|
+
requestContext: storage.safelyParseJSON(row.requestContext),
|
|
3512
3348
|
entity: storage.safelyParseJSON(row.entity),
|
|
3513
3349
|
createdAt: row.createdAtZ || row.createdAt,
|
|
3514
3350
|
updatedAt: row.updatedAtZ || row.updatedAt
|
|
@@ -3546,7 +3382,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3546
3382
|
);
|
|
3547
3383
|
}
|
|
3548
3384
|
}
|
|
3549
|
-
async
|
|
3385
|
+
async listScoresByScorerId({
|
|
3550
3386
|
scorerId,
|
|
3551
3387
|
pagination,
|
|
3552
3388
|
entityId,
|
|
@@ -3574,27 +3410,32 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3574
3410
|
`SELECT COUNT(*) FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE ${whereClause}`,
|
|
3575
3411
|
queryParams
|
|
3576
3412
|
);
|
|
3413
|
+
const { page, perPage: perPageInput } = pagination;
|
|
3414
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
3415
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
3577
3416
|
if (total?.count === "0" || !total?.count) {
|
|
3578
3417
|
return {
|
|
3579
3418
|
pagination: {
|
|
3580
3419
|
total: 0,
|
|
3581
|
-
page
|
|
3582
|
-
perPage:
|
|
3420
|
+
page,
|
|
3421
|
+
perPage: perPageForResponse,
|
|
3583
3422
|
hasMore: false
|
|
3584
3423
|
},
|
|
3585
3424
|
scores: []
|
|
3586
3425
|
};
|
|
3587
3426
|
}
|
|
3427
|
+
const limitValue = perPageInput === false ? Number(total?.count) : perPage;
|
|
3428
|
+
const end = perPageInput === false ? Number(total?.count) : start + perPage;
|
|
3588
3429
|
const result = await this.client.manyOrNone(
|
|
3589
3430
|
`SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`,
|
|
3590
|
-
[...queryParams,
|
|
3431
|
+
[...queryParams, limitValue, start]
|
|
3591
3432
|
);
|
|
3592
3433
|
return {
|
|
3593
3434
|
pagination: {
|
|
3594
3435
|
total: Number(total?.count) || 0,
|
|
3595
|
-
page
|
|
3596
|
-
perPage:
|
|
3597
|
-
hasMore: Number(total?.count)
|
|
3436
|
+
page,
|
|
3437
|
+
perPage: perPageForResponse,
|
|
3438
|
+
hasMore: end < Number(total?.count)
|
|
3598
3439
|
},
|
|
3599
3440
|
scores: result.map(transformScoreRow)
|
|
3600
3441
|
};
|
|
@@ -3612,7 +3453,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3612
3453
|
async saveScore(score) {
|
|
3613
3454
|
let parsedScore;
|
|
3614
3455
|
try {
|
|
3615
|
-
parsedScore =
|
|
3456
|
+
parsedScore = evals.saveScorePayloadSchema.parse(score);
|
|
3616
3457
|
} catch (error$1) {
|
|
3617
3458
|
throw new error.MastraError(
|
|
3618
3459
|
{
|
|
@@ -3620,7 +3461,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3620
3461
|
domain: error.ErrorDomain.STORAGE,
|
|
3621
3462
|
category: error.ErrorCategory.USER,
|
|
3622
3463
|
details: {
|
|
3623
|
-
scorer: score.scorer.
|
|
3464
|
+
scorer: score.scorer.id,
|
|
3624
3465
|
entityId: score.entityId,
|
|
3625
3466
|
entityType: score.entityType,
|
|
3626
3467
|
traceId: score.traceId || "",
|
|
@@ -3640,7 +3481,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3640
3481
|
input,
|
|
3641
3482
|
output,
|
|
3642
3483
|
additionalContext,
|
|
3643
|
-
|
|
3484
|
+
requestContext,
|
|
3644
3485
|
entity,
|
|
3645
3486
|
...rest
|
|
3646
3487
|
} = parsedScore;
|
|
@@ -3656,7 +3497,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3656
3497
|
analyzeStepResult: analyzeStepResult ? JSON.stringify(analyzeStepResult) : null,
|
|
3657
3498
|
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
3658
3499
|
additionalContext: additionalContext ? JSON.stringify(additionalContext) : null,
|
|
3659
|
-
|
|
3500
|
+
requestContext: requestContext ? JSON.stringify(requestContext) : null,
|
|
3660
3501
|
entity: entity ? JSON.stringify(entity) : null,
|
|
3661
3502
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3662
3503
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -3675,7 +3516,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3675
3516
|
);
|
|
3676
3517
|
}
|
|
3677
3518
|
}
|
|
3678
|
-
async
|
|
3519
|
+
async listScoresByRunId({
|
|
3679
3520
|
runId,
|
|
3680
3521
|
pagination
|
|
3681
3522
|
}) {
|
|
@@ -3684,27 +3525,32 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3684
3525
|
`SELECT COUNT(*) FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE "runId" = $1`,
|
|
3685
3526
|
[runId]
|
|
3686
3527
|
);
|
|
3528
|
+
const { page, perPage: perPageInput } = pagination;
|
|
3529
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
3530
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
3687
3531
|
if (total?.count === "0" || !total?.count) {
|
|
3688
3532
|
return {
|
|
3689
3533
|
pagination: {
|
|
3690
3534
|
total: 0,
|
|
3691
|
-
page
|
|
3692
|
-
perPage:
|
|
3535
|
+
page,
|
|
3536
|
+
perPage: perPageForResponse,
|
|
3693
3537
|
hasMore: false
|
|
3694
3538
|
},
|
|
3695
3539
|
scores: []
|
|
3696
3540
|
};
|
|
3697
3541
|
}
|
|
3542
|
+
const limitValue = perPageInput === false ? Number(total?.count) : perPage;
|
|
3543
|
+
const end = perPageInput === false ? Number(total?.count) : start + perPage;
|
|
3698
3544
|
const result = await this.client.manyOrNone(
|
|
3699
3545
|
`SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE "runId" = $1 LIMIT $2 OFFSET $3`,
|
|
3700
|
-
[runId,
|
|
3546
|
+
[runId, limitValue, start]
|
|
3701
3547
|
);
|
|
3702
3548
|
return {
|
|
3703
3549
|
pagination: {
|
|
3704
3550
|
total: Number(total?.count) || 0,
|
|
3705
|
-
page
|
|
3706
|
-
perPage:
|
|
3707
|
-
hasMore: Number(total?.count)
|
|
3551
|
+
page,
|
|
3552
|
+
perPage: perPageForResponse,
|
|
3553
|
+
hasMore: end < Number(total?.count)
|
|
3708
3554
|
},
|
|
3709
3555
|
scores: result.map(transformScoreRow)
|
|
3710
3556
|
};
|
|
@@ -3719,7 +3565,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3719
3565
|
);
|
|
3720
3566
|
}
|
|
3721
3567
|
}
|
|
3722
|
-
async
|
|
3568
|
+
async listScoresByEntityId({
|
|
3723
3569
|
entityId,
|
|
3724
3570
|
entityType,
|
|
3725
3571
|
pagination
|
|
@@ -3729,27 +3575,32 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3729
3575
|
`SELECT COUNT(*) FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE "entityId" = $1 AND "entityType" = $2`,
|
|
3730
3576
|
[entityId, entityType]
|
|
3731
3577
|
);
|
|
3578
|
+
const { page, perPage: perPageInput } = pagination;
|
|
3579
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
3580
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
3732
3581
|
if (total?.count === "0" || !total?.count) {
|
|
3733
3582
|
return {
|
|
3734
3583
|
pagination: {
|
|
3735
3584
|
total: 0,
|
|
3736
|
-
page
|
|
3737
|
-
perPage:
|
|
3585
|
+
page,
|
|
3586
|
+
perPage: perPageForResponse,
|
|
3738
3587
|
hasMore: false
|
|
3739
3588
|
},
|
|
3740
3589
|
scores: []
|
|
3741
3590
|
};
|
|
3742
3591
|
}
|
|
3592
|
+
const limitValue = perPageInput === false ? Number(total?.count) : perPage;
|
|
3593
|
+
const end = perPageInput === false ? Number(total?.count) : start + perPage;
|
|
3743
3594
|
const result = await this.client.manyOrNone(
|
|
3744
3595
|
`SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: this.schema })} WHERE "entityId" = $1 AND "entityType" = $2 LIMIT $3 OFFSET $4`,
|
|
3745
|
-
[entityId, entityType,
|
|
3596
|
+
[entityId, entityType, limitValue, start]
|
|
3746
3597
|
);
|
|
3747
3598
|
return {
|
|
3748
3599
|
pagination: {
|
|
3749
3600
|
total: Number(total?.count) || 0,
|
|
3750
|
-
page
|
|
3751
|
-
perPage:
|
|
3752
|
-
hasMore: Number(total?.count)
|
|
3601
|
+
page,
|
|
3602
|
+
perPage: perPageForResponse,
|
|
3603
|
+
hasMore: end < Number(total?.count)
|
|
3753
3604
|
},
|
|
3754
3605
|
scores: result.map(transformScoreRow)
|
|
3755
3606
|
};
|
|
@@ -3764,7 +3615,7 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3764
3615
|
);
|
|
3765
3616
|
}
|
|
3766
3617
|
}
|
|
3767
|
-
async
|
|
3618
|
+
async listScoresBySpan({
|
|
3768
3619
|
traceId,
|
|
3769
3620
|
spanId,
|
|
3770
3621
|
pagination
|
|
@@ -3776,18 +3627,23 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3776
3627
|
[traceId, spanId]
|
|
3777
3628
|
);
|
|
3778
3629
|
const total = Number(countSQLResult?.count ?? 0);
|
|
3630
|
+
const { page, perPage: perPageInput } = pagination;
|
|
3631
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
3632
|
+
const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
3633
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
3634
|
+
const end = perPageInput === false ? total : start + perPage;
|
|
3779
3635
|
const result = await this.client.manyOrNone(
|
|
3780
3636
|
`SELECT * FROM ${tableName} WHERE "traceId" = $1 AND "spanId" = $2 ORDER BY "createdAt" DESC LIMIT $3 OFFSET $4`,
|
|
3781
|
-
[traceId, spanId,
|
|
3637
|
+
[traceId, spanId, limitValue, start]
|
|
3782
3638
|
);
|
|
3783
|
-
const hasMore =
|
|
3784
|
-
const scores = result.
|
|
3639
|
+
const hasMore = end < total;
|
|
3640
|
+
const scores = result.map((row) => transformScoreRow(row)) ?? [];
|
|
3785
3641
|
return {
|
|
3786
3642
|
scores,
|
|
3787
3643
|
pagination: {
|
|
3788
3644
|
total,
|
|
3789
|
-
page
|
|
3790
|
-
perPage:
|
|
3645
|
+
page,
|
|
3646
|
+
perPage: perPageForResponse,
|
|
3791
3647
|
hasMore
|
|
3792
3648
|
}
|
|
3793
3649
|
};
|
|
@@ -3803,141 +3659,6 @@ var ScoresPG = class extends storage.ScoresStorage {
|
|
|
3803
3659
|
}
|
|
3804
3660
|
}
|
|
3805
3661
|
};
|
|
3806
|
-
var TracesPG = class extends storage.TracesStorage {
|
|
3807
|
-
client;
|
|
3808
|
-
operations;
|
|
3809
|
-
schema;
|
|
3810
|
-
constructor({
|
|
3811
|
-
client,
|
|
3812
|
-
operations,
|
|
3813
|
-
schema
|
|
3814
|
-
}) {
|
|
3815
|
-
super();
|
|
3816
|
-
this.client = client;
|
|
3817
|
-
this.operations = operations;
|
|
3818
|
-
this.schema = schema;
|
|
3819
|
-
}
|
|
3820
|
-
async getTraces(args) {
|
|
3821
|
-
if (args.fromDate || args.toDate) {
|
|
3822
|
-
args.dateRange = {
|
|
3823
|
-
start: args.fromDate,
|
|
3824
|
-
end: args.toDate
|
|
3825
|
-
};
|
|
3826
|
-
}
|
|
3827
|
-
try {
|
|
3828
|
-
const result = await this.getTracesPaginated(args);
|
|
3829
|
-
return result.traces;
|
|
3830
|
-
} catch (error$1) {
|
|
3831
|
-
throw new error.MastraError(
|
|
3832
|
-
{
|
|
3833
|
-
id: "MASTRA_STORAGE_PG_STORE_GET_TRACES_FAILED",
|
|
3834
|
-
domain: error.ErrorDomain.STORAGE,
|
|
3835
|
-
category: error.ErrorCategory.THIRD_PARTY
|
|
3836
|
-
},
|
|
3837
|
-
error$1
|
|
3838
|
-
);
|
|
3839
|
-
}
|
|
3840
|
-
}
|
|
3841
|
-
async getTracesPaginated(args) {
|
|
3842
|
-
const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
|
|
3843
|
-
const fromDate = dateRange?.start;
|
|
3844
|
-
const toDate = dateRange?.end;
|
|
3845
|
-
const currentOffset = page * perPage;
|
|
3846
|
-
const queryParams = [];
|
|
3847
|
-
const conditions = [];
|
|
3848
|
-
let paramIndex = 1;
|
|
3849
|
-
if (name) {
|
|
3850
|
-
conditions.push(`name LIKE $${paramIndex++}`);
|
|
3851
|
-
queryParams.push(`${name}%`);
|
|
3852
|
-
}
|
|
3853
|
-
if (scope) {
|
|
3854
|
-
conditions.push(`scope = $${paramIndex++}`);
|
|
3855
|
-
queryParams.push(scope);
|
|
3856
|
-
}
|
|
3857
|
-
if (attributes) {
|
|
3858
|
-
Object.entries(attributes).forEach(([key, value]) => {
|
|
3859
|
-
const parsedKey = utils.parseFieldKey(key);
|
|
3860
|
-
conditions.push(`attributes->>'${parsedKey}' = $${paramIndex++}`);
|
|
3861
|
-
queryParams.push(value);
|
|
3862
|
-
});
|
|
3863
|
-
}
|
|
3864
|
-
if (filters) {
|
|
3865
|
-
Object.entries(filters).forEach(([key, value]) => {
|
|
3866
|
-
const parsedKey = utils.parseFieldKey(key);
|
|
3867
|
-
conditions.push(`"${parsedKey}" = $${paramIndex++}`);
|
|
3868
|
-
queryParams.push(value);
|
|
3869
|
-
});
|
|
3870
|
-
}
|
|
3871
|
-
if (fromDate) {
|
|
3872
|
-
conditions.push(`"createdAt" >= $${paramIndex++}`);
|
|
3873
|
-
queryParams.push(fromDate);
|
|
3874
|
-
}
|
|
3875
|
-
if (toDate) {
|
|
3876
|
-
conditions.push(`"createdAt" <= $${paramIndex++}`);
|
|
3877
|
-
queryParams.push(toDate);
|
|
3878
|
-
}
|
|
3879
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
3880
|
-
try {
|
|
3881
|
-
const countResult = await this.client.oneOrNone(
|
|
3882
|
-
`SELECT COUNT(*) FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`,
|
|
3883
|
-
queryParams
|
|
3884
|
-
);
|
|
3885
|
-
const total = Number(countResult?.count ?? 0);
|
|
3886
|
-
if (total === 0) {
|
|
3887
|
-
return {
|
|
3888
|
-
traces: [],
|
|
3889
|
-
total: 0,
|
|
3890
|
-
page,
|
|
3891
|
-
perPage,
|
|
3892
|
-
hasMore: false
|
|
3893
|
-
};
|
|
3894
|
-
}
|
|
3895
|
-
const dataResult = await this.client.manyOrNone(
|
|
3896
|
-
`SELECT * FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause} ORDER BY "startTime" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`,
|
|
3897
|
-
[...queryParams, perPage, currentOffset]
|
|
3898
|
-
);
|
|
3899
|
-
const traces = dataResult.map((row) => ({
|
|
3900
|
-
id: row.id,
|
|
3901
|
-
parentSpanId: row.parentSpanId,
|
|
3902
|
-
traceId: row.traceId,
|
|
3903
|
-
name: row.name,
|
|
3904
|
-
scope: row.scope,
|
|
3905
|
-
kind: row.kind,
|
|
3906
|
-
status: storage.safelyParseJSON(row.status),
|
|
3907
|
-
events: storage.safelyParseJSON(row.events),
|
|
3908
|
-
links: storage.safelyParseJSON(row.links),
|
|
3909
|
-
attributes: storage.safelyParseJSON(row.attributes),
|
|
3910
|
-
startTime: row.startTime,
|
|
3911
|
-
endTime: row.endTime,
|
|
3912
|
-
other: storage.safelyParseJSON(row.other),
|
|
3913
|
-
createdAt: row.createdAtZ || row.createdAt
|
|
3914
|
-
}));
|
|
3915
|
-
return {
|
|
3916
|
-
traces,
|
|
3917
|
-
total,
|
|
3918
|
-
page,
|
|
3919
|
-
perPage,
|
|
3920
|
-
hasMore: currentOffset + traces.length < total
|
|
3921
|
-
};
|
|
3922
|
-
} catch (error$1) {
|
|
3923
|
-
throw new error.MastraError(
|
|
3924
|
-
{
|
|
3925
|
-
id: "MASTRA_STORAGE_PG_STORE_GET_TRACES_PAGINATED_FAILED",
|
|
3926
|
-
domain: error.ErrorDomain.STORAGE,
|
|
3927
|
-
category: error.ErrorCategory.THIRD_PARTY
|
|
3928
|
-
},
|
|
3929
|
-
error$1
|
|
3930
|
-
);
|
|
3931
|
-
}
|
|
3932
|
-
}
|
|
3933
|
-
async batchTraceInsert({ records }) {
|
|
3934
|
-
this.logger.debug("Batch inserting traces", { count: records.length });
|
|
3935
|
-
await this.operations.batchInsert({
|
|
3936
|
-
tableName: storage.TABLE_TRACES,
|
|
3937
|
-
records
|
|
3938
|
-
});
|
|
3939
|
-
}
|
|
3940
|
-
};
|
|
3941
3662
|
function parseWorkflowRun(row) {
|
|
3942
3663
|
let parsedSnapshot = row.snapshot;
|
|
3943
3664
|
if (typeof parsedSnapshot === "string") {
|
|
@@ -3975,7 +3696,7 @@ var WorkflowsPG = class extends storage.WorkflowsStorage {
|
|
|
3975
3696
|
// runId,
|
|
3976
3697
|
// stepId,
|
|
3977
3698
|
// result,
|
|
3978
|
-
//
|
|
3699
|
+
// requestContext,
|
|
3979
3700
|
}) {
|
|
3980
3701
|
throw new Error("Method not implemented.");
|
|
3981
3702
|
}
|
|
@@ -4078,12 +3799,12 @@ var WorkflowsPG = class extends storage.WorkflowsStorage {
|
|
|
4078
3799
|
);
|
|
4079
3800
|
}
|
|
4080
3801
|
}
|
|
4081
|
-
async
|
|
3802
|
+
async listWorkflowRuns({
|
|
4082
3803
|
workflowName,
|
|
4083
3804
|
fromDate,
|
|
4084
3805
|
toDate,
|
|
4085
|
-
|
|
4086
|
-
|
|
3806
|
+
perPage,
|
|
3807
|
+
page,
|
|
4087
3808
|
resourceId
|
|
4088
3809
|
} = {}) {
|
|
4089
3810
|
try {
|
|
@@ -4117,20 +3838,23 @@ var WorkflowsPG = class extends storage.WorkflowsStorage {
|
|
|
4117
3838
|
}
|
|
4118
3839
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
4119
3840
|
let total = 0;
|
|
4120
|
-
|
|
3841
|
+
const usePagination = typeof perPage === "number" && typeof page === "number";
|
|
3842
|
+
if (usePagination) {
|
|
4121
3843
|
const countResult = await this.client.one(
|
|
4122
3844
|
`SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: this.schema })} ${whereClause}`,
|
|
4123
3845
|
values
|
|
4124
3846
|
);
|
|
4125
3847
|
total = Number(countResult.count);
|
|
4126
3848
|
}
|
|
3849
|
+
const normalizedPerPage = usePagination ? storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER) : 0;
|
|
3850
|
+
const offset = usePagination ? page * normalizedPerPage : void 0;
|
|
4127
3851
|
const query = `
|
|
4128
3852
|
SELECT * FROM ${getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: this.schema })}
|
|
4129
3853
|
${whereClause}
|
|
4130
3854
|
ORDER BY "createdAt" DESC
|
|
4131
|
-
${
|
|
3855
|
+
${usePagination ? ` LIMIT $${paramIndex} OFFSET $${paramIndex + 1}` : ""}
|
|
4132
3856
|
`;
|
|
4133
|
-
const queryValues =
|
|
3857
|
+
const queryValues = usePagination ? [...values, normalizedPerPage, offset] : values;
|
|
4134
3858
|
const result = await this.client.manyOrNone(query, queryValues);
|
|
4135
3859
|
const runs = (result || []).map((row) => {
|
|
4136
3860
|
return parseWorkflowRun(row);
|
|
@@ -4139,7 +3863,7 @@ var WorkflowsPG = class extends storage.WorkflowsStorage {
|
|
|
4139
3863
|
} catch (error$1) {
|
|
4140
3864
|
throw new error.MastraError(
|
|
4141
3865
|
{
|
|
4142
|
-
id: "
|
|
3866
|
+
id: "MASTRA_STORAGE_PG_STORE_LIST_WORKFLOW_RUNS_FAILED",
|
|
4143
3867
|
domain: error.ErrorDomain.STORAGE,
|
|
4144
3868
|
category: error.ErrorCategory.THIRD_PARTY,
|
|
4145
3869
|
details: {
|
|
@@ -4163,10 +3887,11 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4163
3887
|
constructor(config) {
|
|
4164
3888
|
try {
|
|
4165
3889
|
validateConfig("PostgresStore", config);
|
|
4166
|
-
super({ name: "PostgresStore" });
|
|
3890
|
+
super({ id: config.id, name: "PostgresStore" });
|
|
4167
3891
|
this.schema = config.schemaName || "public";
|
|
4168
3892
|
if (isConnectionStringConfig(config)) {
|
|
4169
3893
|
this.#config = {
|
|
3894
|
+
id: config.id,
|
|
4170
3895
|
connectionString: config.connectionString,
|
|
4171
3896
|
max: config.max,
|
|
4172
3897
|
idleTimeoutMillis: config.idleTimeoutMillis,
|
|
@@ -4175,11 +3900,13 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4175
3900
|
} else if (isCloudSqlConfig(config)) {
|
|
4176
3901
|
this.#config = {
|
|
4177
3902
|
...config,
|
|
3903
|
+
id: config.id,
|
|
4178
3904
|
max: config.max,
|
|
4179
3905
|
idleTimeoutMillis: config.idleTimeoutMillis
|
|
4180
3906
|
};
|
|
4181
3907
|
} else if (isHostConfig(config)) {
|
|
4182
3908
|
this.#config = {
|
|
3909
|
+
id: config.id,
|
|
4183
3910
|
host: config.host,
|
|
4184
3911
|
port: config.port,
|
|
4185
3912
|
database: config.database,
|
|
@@ -4216,17 +3943,13 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4216
3943
|
this.#db = this.#pgp(this.#config);
|
|
4217
3944
|
const operations = new StoreOperationsPG({ client: this.#db, schemaName: this.schema });
|
|
4218
3945
|
const scores = new ScoresPG({ client: this.#db, operations, schema: this.schema });
|
|
4219
|
-
const traces = new TracesPG({ client: this.#db, operations, schema: this.schema });
|
|
4220
3946
|
const workflows = new WorkflowsPG({ client: this.#db, operations, schema: this.schema });
|
|
4221
|
-
const legacyEvals = new LegacyEvalsPG({ client: this.#db, schema: this.schema });
|
|
4222
3947
|
const memory = new MemoryPG({ client: this.#db, schema: this.schema, operations });
|
|
4223
3948
|
const observability = new ObservabilityPG({ client: this.#db, operations, schema: this.schema });
|
|
4224
3949
|
this.stores = {
|
|
4225
3950
|
operations,
|
|
4226
3951
|
scores,
|
|
4227
|
-
traces,
|
|
4228
3952
|
workflows,
|
|
4229
|
-
legacyEvals,
|
|
4230
3953
|
memory,
|
|
4231
3954
|
observability
|
|
4232
3955
|
};
|
|
@@ -4267,30 +3990,11 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4267
3990
|
hasColumn: true,
|
|
4268
3991
|
createTable: true,
|
|
4269
3992
|
deleteMessages: true,
|
|
4270
|
-
|
|
3993
|
+
observabilityInstance: true,
|
|
4271
3994
|
indexManagement: true,
|
|
4272
|
-
|
|
3995
|
+
listScoresBySpan: true
|
|
4273
3996
|
};
|
|
4274
3997
|
}
|
|
4275
|
-
/** @deprecated use getEvals instead */
|
|
4276
|
-
async getEvalsByAgentName(agentName, type) {
|
|
4277
|
-
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
4278
|
-
}
|
|
4279
|
-
async getEvals(options = {}) {
|
|
4280
|
-
return this.stores.legacyEvals.getEvals(options);
|
|
4281
|
-
}
|
|
4282
|
-
/**
|
|
4283
|
-
* @deprecated use getTracesPaginated instead
|
|
4284
|
-
*/
|
|
4285
|
-
async getTraces(args) {
|
|
4286
|
-
return this.stores.traces.getTraces(args);
|
|
4287
|
-
}
|
|
4288
|
-
async getTracesPaginated(args) {
|
|
4289
|
-
return this.stores.traces.getTracesPaginated(args);
|
|
4290
|
-
}
|
|
4291
|
-
async batchTraceInsert({ records }) {
|
|
4292
|
-
return this.stores.traces.batchTraceInsert({ records });
|
|
4293
|
-
}
|
|
4294
3998
|
async createTable({
|
|
4295
3999
|
tableName,
|
|
4296
4000
|
schema
|
|
@@ -4325,15 +4029,6 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4325
4029
|
async getThreadById({ threadId }) {
|
|
4326
4030
|
return this.stores.memory.getThreadById({ threadId });
|
|
4327
4031
|
}
|
|
4328
|
-
/**
|
|
4329
|
-
* @deprecated use getThreadsByResourceIdPaginated instead
|
|
4330
|
-
*/
|
|
4331
|
-
async getThreadsByResourceId(args) {
|
|
4332
|
-
return this.stores.memory.getThreadsByResourceId(args);
|
|
4333
|
-
}
|
|
4334
|
-
async getThreadsByResourceIdPaginated(args) {
|
|
4335
|
-
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
4336
|
-
}
|
|
4337
4032
|
async saveThread({ thread }) {
|
|
4338
4033
|
return this.stores.memory.saveThread({ thread });
|
|
4339
4034
|
}
|
|
@@ -4347,17 +4042,8 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4347
4042
|
async deleteThread({ threadId }) {
|
|
4348
4043
|
return this.stores.memory.deleteThread({ threadId });
|
|
4349
4044
|
}
|
|
4350
|
-
async
|
|
4351
|
-
return this.stores.memory.
|
|
4352
|
-
}
|
|
4353
|
-
async getMessagesById({
|
|
4354
|
-
messageIds,
|
|
4355
|
-
format
|
|
4356
|
-
}) {
|
|
4357
|
-
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
4358
|
-
}
|
|
4359
|
-
async getMessagesPaginated(args) {
|
|
4360
|
-
return this.stores.memory.getMessagesPaginated(args);
|
|
4045
|
+
async listMessagesById({ messageIds }) {
|
|
4046
|
+
return this.stores.memory.listMessagesById({ messageIds });
|
|
4361
4047
|
}
|
|
4362
4048
|
async saveMessages(args) {
|
|
4363
4049
|
return this.stores.memory.saveMessages(args);
|
|
@@ -4391,9 +4077,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4391
4077
|
runId,
|
|
4392
4078
|
stepId,
|
|
4393
4079
|
result,
|
|
4394
|
-
|
|
4080
|
+
requestContext
|
|
4395
4081
|
}) {
|
|
4396
|
-
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result,
|
|
4082
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
|
|
4397
4083
|
}
|
|
4398
4084
|
async updateWorkflowState({
|
|
4399
4085
|
workflowName,
|
|
@@ -4416,15 +4102,15 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4416
4102
|
}) {
|
|
4417
4103
|
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
4418
4104
|
}
|
|
4419
|
-
async
|
|
4105
|
+
async listWorkflowRuns({
|
|
4420
4106
|
workflowName,
|
|
4421
4107
|
fromDate,
|
|
4422
4108
|
toDate,
|
|
4423
|
-
|
|
4424
|
-
|
|
4109
|
+
perPage,
|
|
4110
|
+
page,
|
|
4425
4111
|
resourceId
|
|
4426
4112
|
} = {}) {
|
|
4427
|
-
return this.stores.workflows.
|
|
4113
|
+
return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
|
|
4428
4114
|
}
|
|
4429
4115
|
async getWorkflowRunById({
|
|
4430
4116
|
runId,
|
|
@@ -4436,9 +4122,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4436
4122
|
this.pgp.end();
|
|
4437
4123
|
}
|
|
4438
4124
|
/**
|
|
4439
|
-
*
|
|
4125
|
+
* Tracing / Observability
|
|
4440
4126
|
*/
|
|
4441
|
-
async
|
|
4127
|
+
async createSpan(span) {
|
|
4442
4128
|
if (!this.stores.observability) {
|
|
4443
4129
|
throw new error.MastraError({
|
|
4444
4130
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4447,9 +4133,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4447
4133
|
text: "Observability storage is not initialized"
|
|
4448
4134
|
});
|
|
4449
4135
|
}
|
|
4450
|
-
return this.stores.observability.
|
|
4136
|
+
return this.stores.observability.createSpan(span);
|
|
4451
4137
|
}
|
|
4452
|
-
async
|
|
4138
|
+
async updateSpan({
|
|
4453
4139
|
spanId,
|
|
4454
4140
|
traceId,
|
|
4455
4141
|
updates
|
|
@@ -4462,9 +4148,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4462
4148
|
text: "Observability storage is not initialized"
|
|
4463
4149
|
});
|
|
4464
4150
|
}
|
|
4465
|
-
return this.stores.observability.
|
|
4151
|
+
return this.stores.observability.updateSpan({ spanId, traceId, updates });
|
|
4466
4152
|
}
|
|
4467
|
-
async
|
|
4153
|
+
async getTrace(traceId) {
|
|
4468
4154
|
if (!this.stores.observability) {
|
|
4469
4155
|
throw new error.MastraError({
|
|
4470
4156
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4473,9 +4159,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4473
4159
|
text: "Observability storage is not initialized"
|
|
4474
4160
|
});
|
|
4475
4161
|
}
|
|
4476
|
-
return this.stores.observability.
|
|
4162
|
+
return this.stores.observability.getTrace(traceId);
|
|
4477
4163
|
}
|
|
4478
|
-
async
|
|
4164
|
+
async getTracesPaginated(args) {
|
|
4479
4165
|
if (!this.stores.observability) {
|
|
4480
4166
|
throw new error.MastraError({
|
|
4481
4167
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4484,9 +4170,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4484
4170
|
text: "Observability storage is not initialized"
|
|
4485
4171
|
});
|
|
4486
4172
|
}
|
|
4487
|
-
return this.stores.observability.
|
|
4173
|
+
return this.stores.observability.getTracesPaginated(args);
|
|
4488
4174
|
}
|
|
4489
|
-
async
|
|
4175
|
+
async batchCreateSpans(args) {
|
|
4490
4176
|
if (!this.stores.observability) {
|
|
4491
4177
|
throw new error.MastraError({
|
|
4492
4178
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4495,9 +4181,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4495
4181
|
text: "Observability storage is not initialized"
|
|
4496
4182
|
});
|
|
4497
4183
|
}
|
|
4498
|
-
return this.stores.observability.
|
|
4184
|
+
return this.stores.observability.batchCreateSpans(args);
|
|
4499
4185
|
}
|
|
4500
|
-
async
|
|
4186
|
+
async batchUpdateSpans(args) {
|
|
4501
4187
|
if (!this.stores.observability) {
|
|
4502
4188
|
throw new error.MastraError({
|
|
4503
4189
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4506,9 +4192,9 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4506
4192
|
text: "Observability storage is not initialized"
|
|
4507
4193
|
});
|
|
4508
4194
|
}
|
|
4509
|
-
return this.stores.observability.
|
|
4195
|
+
return this.stores.observability.batchUpdateSpans(args);
|
|
4510
4196
|
}
|
|
4511
|
-
async
|
|
4197
|
+
async batchDeleteTraces(args) {
|
|
4512
4198
|
if (!this.stores.observability) {
|
|
4513
4199
|
throw new error.MastraError({
|
|
4514
4200
|
id: "PG_STORE_OBSERVABILITY_NOT_INITIALIZED",
|
|
@@ -4517,7 +4203,7 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4517
4203
|
text: "Observability storage is not initialized"
|
|
4518
4204
|
});
|
|
4519
4205
|
}
|
|
4520
|
-
return this.stores.observability.
|
|
4206
|
+
return this.stores.observability.batchDeleteTraces(args);
|
|
4521
4207
|
}
|
|
4522
4208
|
/**
|
|
4523
4209
|
* Scorers
|
|
@@ -4525,41 +4211,41 @@ var PostgresStore = class extends storage.MastraStorage {
|
|
|
4525
4211
|
async getScoreById({ id }) {
|
|
4526
4212
|
return this.stores.scores.getScoreById({ id });
|
|
4527
4213
|
}
|
|
4528
|
-
async
|
|
4214
|
+
async listScoresByScorerId({
|
|
4529
4215
|
scorerId,
|
|
4530
4216
|
pagination,
|
|
4531
4217
|
entityId,
|
|
4532
4218
|
entityType,
|
|
4533
4219
|
source
|
|
4534
4220
|
}) {
|
|
4535
|
-
return this.stores.scores.
|
|
4221
|
+
return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
4536
4222
|
}
|
|
4537
4223
|
async saveScore(score) {
|
|
4538
4224
|
return this.stores.scores.saveScore(score);
|
|
4539
4225
|
}
|
|
4540
|
-
async
|
|
4226
|
+
async listScoresByRunId({
|
|
4541
4227
|
runId,
|
|
4542
4228
|
pagination
|
|
4543
4229
|
}) {
|
|
4544
|
-
return this.stores.scores.
|
|
4230
|
+
return this.stores.scores.listScoresByRunId({ runId, pagination });
|
|
4545
4231
|
}
|
|
4546
|
-
async
|
|
4232
|
+
async listScoresByEntityId({
|
|
4547
4233
|
entityId,
|
|
4548
4234
|
entityType,
|
|
4549
4235
|
pagination
|
|
4550
4236
|
}) {
|
|
4551
|
-
return this.stores.scores.
|
|
4237
|
+
return this.stores.scores.listScoresByEntityId({
|
|
4552
4238
|
entityId,
|
|
4553
4239
|
entityType,
|
|
4554
4240
|
pagination
|
|
4555
4241
|
});
|
|
4556
4242
|
}
|
|
4557
|
-
async
|
|
4243
|
+
async listScoresBySpan({
|
|
4558
4244
|
traceId,
|
|
4559
4245
|
spanId,
|
|
4560
4246
|
pagination
|
|
4561
4247
|
}) {
|
|
4562
|
-
return this.stores.scores.
|
|
4248
|
+
return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
|
|
4563
4249
|
}
|
|
4564
4250
|
};
|
|
4565
4251
|
|