@mastra/pg 1.2.0 → 1.3.0-alpha.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 +91 -0
- package/dist/docs/SKILL.md +28 -25
- package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
- package/dist/docs/{memory/03-semantic-recall.md → references/docs-memory-semantic-recall.md} +33 -17
- package/dist/docs/{memory/01-storage.md → references/docs-memory-storage.md} +29 -39
- package/dist/docs/{memory/02-working-memory.md → references/docs-memory-working-memory.md} +16 -27
- package/dist/docs/{rag/01-overview.md → references/docs-rag-overview.md} +2 -4
- package/dist/docs/{rag/03-retrieval.md → references/docs-rag-retrieval.md} +26 -53
- package/dist/docs/{rag/02-vector-databases.md → references/docs-rag-vector-databases.md} +198 -202
- package/dist/docs/{memory/04-reference.md → references/reference-memory-memory-class.md} +28 -14
- package/dist/docs/references/reference-processors-message-history-processor.md +85 -0
- package/dist/docs/references/reference-processors-semantic-recall-processor.md +123 -0
- package/dist/docs/references/reference-processors-working-memory-processor.md +154 -0
- package/dist/docs/{rag/04-reference.md → references/reference-rag-metadata-filters.md} +26 -179
- package/dist/docs/references/reference-storage-composite.md +235 -0
- package/dist/docs/references/reference-storage-dynamodb.md +282 -0
- package/dist/docs/references/reference-storage-postgresql.md +529 -0
- package/dist/docs/{tools/01-reference.md → references/reference-tools-vector-query-tool.md} +137 -118
- package/dist/docs/{vectors/01-reference.md → references/reference-vectors-pg.md} +115 -14
- package/dist/index.cjs +1998 -217
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1998 -219
- package/dist/index.js.map +1 -1
- package/dist/storage/db/constraint-utils.d.ts +16 -0
- package/dist/storage/db/constraint-utils.d.ts.map +1 -0
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/domains/agents/index.d.ts +9 -12
- package/dist/storage/domains/agents/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +7 -1
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/dist/storage/domains/prompt-blocks/index.d.ts +33 -0
- package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts +33 -0
- package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +3 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +2 -3
- package/dist/docs/README.md +0 -36
- package/dist/docs/processors/01-reference.md +0 -296
- package/dist/docs/storage/01-reference.md +0 -905
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
-
import { createVectorErrorId, TABLE_SCHEMAS, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
|
|
2
|
+
import { createVectorErrorId, TABLE_SCHEMAS, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
|
|
3
3
|
import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
|
|
4
4
|
import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
|
|
5
5
|
import { Mutex } from 'async-mutex';
|
|
@@ -8,6 +8,7 @@ import { Pool } from 'pg';
|
|
|
8
8
|
import xxhash from 'xxhash-wasm';
|
|
9
9
|
import { BaseFilterTranslator } from '@mastra/core/vector/filter';
|
|
10
10
|
import { MastraBase } from '@mastra/core/base';
|
|
11
|
+
import { randomUUID } from 'crypto';
|
|
11
12
|
import { MessageList } from '@mastra/core/agent';
|
|
12
13
|
import { saveScorePayloadSchema } from '@mastra/core/evals';
|
|
13
14
|
|
|
@@ -1882,6 +1883,32 @@ var TransactionClient = class {
|
|
|
1882
1883
|
return Promise.all(promises);
|
|
1883
1884
|
}
|
|
1884
1885
|
};
|
|
1886
|
+
|
|
1887
|
+
// src/storage/db/constraint-utils.ts
|
|
1888
|
+
var POSTGRES_IDENTIFIER_MAX_LENGTH = 63;
|
|
1889
|
+
function truncateIdentifier(value, maxLength = POSTGRES_IDENTIFIER_MAX_LENGTH) {
|
|
1890
|
+
if (maxLength <= 0) return "";
|
|
1891
|
+
if (Buffer.byteLength(value, "utf-8") <= maxLength) return value;
|
|
1892
|
+
let bytes = 0;
|
|
1893
|
+
let end = 0;
|
|
1894
|
+
for (const ch of value) {
|
|
1895
|
+
const chBytes = Buffer.byteLength(ch, "utf-8");
|
|
1896
|
+
if (bytes + chBytes > maxLength) break;
|
|
1897
|
+
bytes += chBytes;
|
|
1898
|
+
end += ch.length;
|
|
1899
|
+
}
|
|
1900
|
+
return value.slice(0, end);
|
|
1901
|
+
}
|
|
1902
|
+
function buildConstraintName({
|
|
1903
|
+
baseName,
|
|
1904
|
+
schemaName,
|
|
1905
|
+
maxLength = POSTGRES_IDENTIFIER_MAX_LENGTH
|
|
1906
|
+
}) {
|
|
1907
|
+
const prefix = schemaName ? `${schemaName}_` : "";
|
|
1908
|
+
return truncateIdentifier(`${prefix}${baseName}`.toLowerCase(), maxLength);
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
// src/storage/db/index.ts
|
|
1885
1912
|
function resolvePgConfig(config) {
|
|
1886
1913
|
if ("client" in config) {
|
|
1887
1914
|
return {
|
|
@@ -1960,8 +1987,16 @@ function generateTableSQL({
|
|
|
1960
1987
|
});
|
|
1961
1988
|
const finalColumns = [...columns, ...timeZColumns].join(",\n");
|
|
1962
1989
|
const parsedSchemaName = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
|
|
1963
|
-
const
|
|
1990
|
+
const workflowSnapshotConstraint = buildConstraintName({
|
|
1991
|
+
baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
|
|
1992
|
+
schemaName: parsedSchemaName || void 0
|
|
1993
|
+
});
|
|
1994
|
+
const spansPrimaryKeyConstraint = buildConstraintName({
|
|
1995
|
+
baseName: "mastra_ai_spans_traceid_spanid_pk",
|
|
1996
|
+
schemaName: parsedSchemaName || void 0
|
|
1997
|
+
});
|
|
1964
1998
|
const quotedSchemaName = getSchemaName(schemaName);
|
|
1999
|
+
const schemaFilter = parsedSchemaName || "public";
|
|
1965
2000
|
const sql = `
|
|
1966
2001
|
CREATE TABLE IF NOT EXISTS ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })} (
|
|
1967
2002
|
${finalColumns}
|
|
@@ -1969,12 +2004,12 @@ function generateTableSQL({
|
|
|
1969
2004
|
${tableName === TABLE_WORKFLOW_SNAPSHOT ? `
|
|
1970
2005
|
DO $$ BEGIN
|
|
1971
2006
|
IF NOT EXISTS (
|
|
1972
|
-
SELECT 1 FROM pg_constraint WHERE conname = lower('${
|
|
2007
|
+
SELECT 1 FROM pg_constraint WHERE conname = lower('${workflowSnapshotConstraint}') AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = '${schemaFilter}')
|
|
1973
2008
|
) AND NOT EXISTS (
|
|
1974
|
-
SELECT 1 FROM pg_indexes WHERE indexname = lower('${
|
|
2009
|
+
SELECT 1 FROM pg_indexes WHERE indexname = lower('${workflowSnapshotConstraint}') AND schemaname = '${schemaFilter}'
|
|
1975
2010
|
) THEN
|
|
1976
2011
|
ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
|
|
1977
|
-
ADD CONSTRAINT ${
|
|
2012
|
+
ADD CONSTRAINT ${workflowSnapshotConstraint}
|
|
1978
2013
|
UNIQUE (workflow_name, run_id);
|
|
1979
2014
|
END IF;
|
|
1980
2015
|
END $$;
|
|
@@ -1983,10 +2018,10 @@ function generateTableSQL({
|
|
|
1983
2018
|
tableName === TABLE_SPANS && includeAllConstraints ? `
|
|
1984
2019
|
DO $$ BEGIN
|
|
1985
2020
|
IF NOT EXISTS (
|
|
1986
|
-
SELECT 1 FROM pg_constraint WHERE conname = lower('${
|
|
2021
|
+
SELECT 1 FROM pg_constraint WHERE conname = lower('${spansPrimaryKeyConstraint}') AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = '${schemaFilter}')
|
|
1987
2022
|
) THEN
|
|
1988
2023
|
ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
|
|
1989
|
-
ADD CONSTRAINT ${
|
|
2024
|
+
ADD CONSTRAINT ${spansPrimaryKeyConstraint}
|
|
1990
2025
|
PRIMARY KEY ("traceId", "spanId");
|
|
1991
2026
|
END IF;
|
|
1992
2027
|
END $$;
|
|
@@ -2472,11 +2507,14 @@ Note: This migration may take some time for large tables.
|
|
|
2472
2507
|
*/
|
|
2473
2508
|
async spansPrimaryKeyExists() {
|
|
2474
2509
|
const parsedSchemaName = this.schemaName ? parseSqlIdentifier(this.schemaName, "schema name") : "";
|
|
2475
|
-
const
|
|
2476
|
-
|
|
2510
|
+
const constraintName = buildConstraintName({
|
|
2511
|
+
baseName: "mastra_ai_spans_traceid_spanid_pk",
|
|
2512
|
+
schemaName: parsedSchemaName || void 0
|
|
2513
|
+
});
|
|
2514
|
+
const schemaFilter = this.schemaName || "public";
|
|
2477
2515
|
const result = await this.client.oneOrNone(
|
|
2478
|
-
`SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = $1) as exists`,
|
|
2479
|
-
[constraintName]
|
|
2516
|
+
`SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = lower($1) AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = $2)) as exists`,
|
|
2517
|
+
[constraintName, schemaFilter]
|
|
2480
2518
|
);
|
|
2481
2519
|
return result?.exists ?? false;
|
|
2482
2520
|
}
|
|
@@ -2487,16 +2525,19 @@ Note: This migration may take some time for large tables.
|
|
|
2487
2525
|
async addSpansPrimaryKey() {
|
|
2488
2526
|
const fullTableName = getTableName({ indexName: TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
|
|
2489
2527
|
const parsedSchemaName = this.schemaName ? parseSqlIdentifier(this.schemaName, "schema name") : "";
|
|
2490
|
-
const
|
|
2491
|
-
|
|
2528
|
+
const constraintName = buildConstraintName({
|
|
2529
|
+
baseName: "mastra_ai_spans_traceid_spanid_pk",
|
|
2530
|
+
schemaName: parsedSchemaName || void 0
|
|
2531
|
+
});
|
|
2532
|
+
const schemaFilter = this.schemaName || "public";
|
|
2492
2533
|
try {
|
|
2493
2534
|
const constraintExists = await this.client.oneOrNone(
|
|
2494
2535
|
`
|
|
2495
2536
|
SELECT EXISTS (
|
|
2496
|
-
SELECT 1 FROM pg_constraint WHERE conname = $1
|
|
2537
|
+
SELECT 1 FROM pg_constraint WHERE conname = lower($1) AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = $2)
|
|
2497
2538
|
) as exists
|
|
2498
2539
|
`,
|
|
2499
|
-
[constraintName]
|
|
2540
|
+
[constraintName, schemaFilter]
|
|
2500
2541
|
);
|
|
2501
2542
|
if (constraintExists?.exists) {
|
|
2502
2543
|
this.logger?.debug?.(`PRIMARY KEY constraint ${constraintName} already exists on ${fullTableName}`);
|
|
@@ -3128,6 +3169,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3128
3169
|
schema: TABLE_SCHEMAS[TABLE_AGENTS],
|
|
3129
3170
|
ifNotExists: ["status", "authorId"]
|
|
3130
3171
|
});
|
|
3172
|
+
await this.#migrateToolsToJsonbFormat();
|
|
3131
3173
|
await this.createDefaultIndexes();
|
|
3132
3174
|
await this.createCustomIndexes();
|
|
3133
3175
|
await this.#cleanupStaleDrafts();
|
|
@@ -3188,7 +3230,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3188
3230
|
1,
|
|
3189
3231
|
row.name ?? agentId,
|
|
3190
3232
|
row.description ?? null,
|
|
3191
|
-
row.instructions ?? "",
|
|
3233
|
+
this.serializeInstructions(row.instructions ?? ""),
|
|
3192
3234
|
row.model ? JSON.stringify(row.model) : "{}",
|
|
3193
3235
|
row.tools ? JSON.stringify(row.tools) : null,
|
|
3194
3236
|
row.defaultOptions ? JSON.stringify(row.defaultOptions) : null,
|
|
@@ -3226,6 +3268,45 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3226
3268
|
await this.#db.client.none(`DROP TABLE IF EXISTS ${fullVersionsTableName}`);
|
|
3227
3269
|
await this.#db.client.none(`DROP TABLE IF EXISTS ${legacyTableName}`);
|
|
3228
3270
|
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Migrates the tools field from string[] format to JSONB format { "tool-key": { "description": "..." } }.
|
|
3273
|
+
* This handles the transition from the old format where tools were stored as an array of string keys
|
|
3274
|
+
* to the new format where tools can have per-agent description overrides.
|
|
3275
|
+
*/
|
|
3276
|
+
async #migrateToolsToJsonbFormat() {
|
|
3277
|
+
const fullVersionsTableName = getTableName2({
|
|
3278
|
+
indexName: TABLE_AGENT_VERSIONS,
|
|
3279
|
+
schemaName: getSchemaName2(this.#schema)
|
|
3280
|
+
});
|
|
3281
|
+
try {
|
|
3282
|
+
const recordsWithArrayTools = await this.#db.client.any(
|
|
3283
|
+
`SELECT id, tools FROM ${fullVersionsTableName}
|
|
3284
|
+
WHERE tools IS NOT NULL
|
|
3285
|
+
AND jsonb_typeof(tools) = 'array'`
|
|
3286
|
+
);
|
|
3287
|
+
if (recordsWithArrayTools.length === 0) {
|
|
3288
|
+
return;
|
|
3289
|
+
}
|
|
3290
|
+
for (const record of recordsWithArrayTools) {
|
|
3291
|
+
const toolsArray = record.tools;
|
|
3292
|
+
const toolsObject = {};
|
|
3293
|
+
for (const toolKey of toolsArray) {
|
|
3294
|
+
toolsObject[toolKey] = {};
|
|
3295
|
+
}
|
|
3296
|
+
await this.#db.client.none(
|
|
3297
|
+
`UPDATE ${fullVersionsTableName}
|
|
3298
|
+
SET tools = $1::jsonb
|
|
3299
|
+
WHERE id = $2`,
|
|
3300
|
+
[JSON.stringify(toolsObject), record.id]
|
|
3301
|
+
);
|
|
3302
|
+
}
|
|
3303
|
+
this.logger?.info?.(
|
|
3304
|
+
`Migrated ${recordsWithArrayTools.length} agent version(s) tools from array to object format`
|
|
3305
|
+
);
|
|
3306
|
+
} catch (error) {
|
|
3307
|
+
this.logger?.warn?.("Failed to migrate tools to JSONB format:", error);
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3229
3310
|
/**
|
|
3230
3311
|
* Removes stale draft agent records that have no activeVersionId.
|
|
3231
3312
|
* These are left behind when createAgent partially fails (inserts thin record
|
|
@@ -3263,6 +3344,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3263
3344
|
try {
|
|
3264
3345
|
return JSON.parse(value);
|
|
3265
3346
|
} catch (error) {
|
|
3347
|
+
if (error instanceof MastraError) throw error;
|
|
3266
3348
|
const details = {
|
|
3267
3349
|
value: value.length > 100 ? value.substring(0, 100) + "..." : value
|
|
3268
3350
|
};
|
|
@@ -3292,7 +3374,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3292
3374
|
updatedAt: row.updatedAtZ || row.updatedAt
|
|
3293
3375
|
};
|
|
3294
3376
|
}
|
|
3295
|
-
async
|
|
3377
|
+
async getById(id) {
|
|
3296
3378
|
try {
|
|
3297
3379
|
const tableName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3298
3380
|
const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
|
|
@@ -3301,6 +3383,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3301
3383
|
}
|
|
3302
3384
|
return this.parseRow(result);
|
|
3303
3385
|
} catch (error) {
|
|
3386
|
+
if (error instanceof MastraError) throw error;
|
|
3304
3387
|
throw new MastraError(
|
|
3305
3388
|
{
|
|
3306
3389
|
id: createStorageErrorId("PG", "GET_AGENT_BY_ID", "FAILED"),
|
|
@@ -3312,7 +3395,8 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3312
3395
|
);
|
|
3313
3396
|
}
|
|
3314
3397
|
}
|
|
3315
|
-
async
|
|
3398
|
+
async create(input) {
|
|
3399
|
+
const { agent } = input;
|
|
3316
3400
|
try {
|
|
3317
3401
|
const agentsTable = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3318
3402
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -3356,6 +3440,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3356
3440
|
updatedAt: now
|
|
3357
3441
|
};
|
|
3358
3442
|
} catch (error) {
|
|
3443
|
+
if (error instanceof MastraError) throw error;
|
|
3359
3444
|
try {
|
|
3360
3445
|
const agentsTable = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3361
3446
|
await this.#db.client.none(
|
|
@@ -3375,10 +3460,11 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3375
3460
|
);
|
|
3376
3461
|
}
|
|
3377
3462
|
}
|
|
3378
|
-
async
|
|
3463
|
+
async update(input) {
|
|
3464
|
+
const { id, ...updates } = input;
|
|
3379
3465
|
try {
|
|
3380
3466
|
const tableName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3381
|
-
const existingAgent = await this.
|
|
3467
|
+
const existingAgent = await this.getById(id);
|
|
3382
3468
|
if (!existingAgent) {
|
|
3383
3469
|
throw new MastraError({
|
|
3384
3470
|
id: createStorageErrorId("PG", "UPDATE_AGENT", "NOT_FOUND"),
|
|
@@ -3425,12 +3511,15 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3425
3511
|
createdAt: _createdAt,
|
|
3426
3512
|
...latestConfig
|
|
3427
3513
|
} = latestVersion;
|
|
3514
|
+
const sanitizedConfigFields = Object.fromEntries(
|
|
3515
|
+
Object.entries(configFields).map(([key, value]) => [key, value === null ? void 0 : value])
|
|
3516
|
+
);
|
|
3428
3517
|
const newConfig = {
|
|
3429
3518
|
...latestConfig,
|
|
3430
|
-
...
|
|
3519
|
+
...sanitizedConfigFields
|
|
3431
3520
|
};
|
|
3432
3521
|
const changedFields = configFieldNames.filter(
|
|
3433
|
-
(field) => field in configFields && configFields[field] !== latestConfig[field]
|
|
3522
|
+
(field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
|
|
3434
3523
|
);
|
|
3435
3524
|
if (changedFields.length > 0) {
|
|
3436
3525
|
const newVersionId = crypto.randomUUID();
|
|
@@ -3472,7 +3561,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3472
3561
|
values
|
|
3473
3562
|
);
|
|
3474
3563
|
}
|
|
3475
|
-
const updatedAgent = await this.
|
|
3564
|
+
const updatedAgent = await this.getById(id);
|
|
3476
3565
|
if (!updatedAgent) {
|
|
3477
3566
|
throw new MastraError({
|
|
3478
3567
|
id: createStorageErrorId("PG", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
|
|
@@ -3498,12 +3587,13 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3498
3587
|
);
|
|
3499
3588
|
}
|
|
3500
3589
|
}
|
|
3501
|
-
async
|
|
3590
|
+
async delete(id) {
|
|
3502
3591
|
try {
|
|
3503
3592
|
const tableName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3504
|
-
await this.
|
|
3593
|
+
await this.deleteVersionsByParentId(id);
|
|
3505
3594
|
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
3506
3595
|
} catch (error) {
|
|
3596
|
+
if (error instanceof MastraError) throw error;
|
|
3507
3597
|
throw new MastraError(
|
|
3508
3598
|
{
|
|
3509
3599
|
id: createStorageErrorId("PG", "DELETE_AGENT", "FAILED"),
|
|
@@ -3515,7 +3605,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3515
3605
|
);
|
|
3516
3606
|
}
|
|
3517
3607
|
}
|
|
3518
|
-
async
|
|
3608
|
+
async list(args) {
|
|
3519
3609
|
const { page = 0, perPage: perPageInput, orderBy } = args || {};
|
|
3520
3610
|
const { field, direction } = this.parseOrderBy(orderBy);
|
|
3521
3611
|
if (page < 0) {
|
|
@@ -3558,6 +3648,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3558
3648
|
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
3559
3649
|
};
|
|
3560
3650
|
} catch (error) {
|
|
3651
|
+
if (error instanceof MastraError) throw error;
|
|
3561
3652
|
throw new MastraError(
|
|
3562
3653
|
{
|
|
3563
3654
|
id: createStorageErrorId("PG", "LIST_AGENTS", "FAILED"),
|
|
@@ -3568,124 +3659,6 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3568
3659
|
);
|
|
3569
3660
|
}
|
|
3570
3661
|
}
|
|
3571
|
-
async listAgentsResolved(args) {
|
|
3572
|
-
const { page = 0, perPage: perPageInput, orderBy } = args || {};
|
|
3573
|
-
const { field, direction } = this.parseOrderBy(orderBy);
|
|
3574
|
-
if (page < 0) {
|
|
3575
|
-
throw new MastraError(
|
|
3576
|
-
{
|
|
3577
|
-
id: createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
|
|
3578
|
-
domain: ErrorDomain.STORAGE,
|
|
3579
|
-
category: ErrorCategory.USER,
|
|
3580
|
-
details: { page }
|
|
3581
|
-
},
|
|
3582
|
-
new Error("page must be >= 0")
|
|
3583
|
-
);
|
|
3584
|
-
}
|
|
3585
|
-
const perPage = normalizePerPage(perPageInput, 100);
|
|
3586
|
-
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
3587
|
-
try {
|
|
3588
|
-
const agentsTableName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3589
|
-
const versionsTableName = getTableName2({
|
|
3590
|
-
indexName: TABLE_AGENT_VERSIONS,
|
|
3591
|
-
schemaName: getSchemaName2(this.#schema)
|
|
3592
|
-
});
|
|
3593
|
-
const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${agentsTableName}`);
|
|
3594
|
-
const total = parseInt(countResult.count, 10);
|
|
3595
|
-
if (total === 0) {
|
|
3596
|
-
return {
|
|
3597
|
-
agents: [],
|
|
3598
|
-
total: 0,
|
|
3599
|
-
page,
|
|
3600
|
-
perPage: perPageForResponse,
|
|
3601
|
-
hasMore: false
|
|
3602
|
-
};
|
|
3603
|
-
}
|
|
3604
|
-
const limitValue = perPageInput === false ? total : perPage;
|
|
3605
|
-
const query = `
|
|
3606
|
-
WITH latest_versions AS (
|
|
3607
|
-
SELECT v.*
|
|
3608
|
-
FROM ${versionsTableName} v
|
|
3609
|
-
INNER JOIN (
|
|
3610
|
-
SELECT "agentId", MAX("versionNumber") as max_version
|
|
3611
|
-
FROM ${versionsTableName}
|
|
3612
|
-
GROUP BY "agentId"
|
|
3613
|
-
) lv ON v."agentId" = lv."agentId" AND v."versionNumber" = lv.max_version
|
|
3614
|
-
)
|
|
3615
|
-
SELECT
|
|
3616
|
-
a.*,
|
|
3617
|
-
COALESCE(av.id, lv.id) as version_id,
|
|
3618
|
-
COALESCE(av."versionNumber", lv."versionNumber") as version_number,
|
|
3619
|
-
COALESCE(av.name, lv.name) as version_name,
|
|
3620
|
-
COALESCE(av.description, lv.description) as version_description,
|
|
3621
|
-
COALESCE(av.instructions, lv.instructions) as version_instructions,
|
|
3622
|
-
COALESCE(av.model, lv.model) as version_model,
|
|
3623
|
-
COALESCE(av.tools, lv.tools) as version_tools,
|
|
3624
|
-
COALESCE(av."defaultOptions", lv."defaultOptions") as version_defaultOptions,
|
|
3625
|
-
COALESCE(av.workflows, lv.workflows) as version_workflows,
|
|
3626
|
-
COALESCE(av.agents, lv.agents) as version_agents,
|
|
3627
|
-
COALESCE(av."integrationTools", lv."integrationTools") as version_integrationTools,
|
|
3628
|
-
COALESCE(av."inputProcessors", lv."inputProcessors") as version_inputProcessors,
|
|
3629
|
-
COALESCE(av."outputProcessors", lv."outputProcessors") as version_outputProcessors,
|
|
3630
|
-
COALESCE(av.memory, lv.memory) as version_memory,
|
|
3631
|
-
COALESCE(av.scorers, lv.scorers) as version_scorers
|
|
3632
|
-
FROM ${agentsTableName} a
|
|
3633
|
-
LEFT JOIN ${versionsTableName} av ON a."activeVersionId" = av.id
|
|
3634
|
-
LEFT JOIN latest_versions lv ON a.id = lv."agentId"
|
|
3635
|
-
ORDER BY a."${field}" ${direction}
|
|
3636
|
-
LIMIT $1 OFFSET $2
|
|
3637
|
-
`;
|
|
3638
|
-
const dataResult = await this.#db.client.manyOrNone(query, [limitValue, offset]);
|
|
3639
|
-
const resolvedAgents = (dataResult || []).map((row) => {
|
|
3640
|
-
const agent = this.parseRow({
|
|
3641
|
-
id: row.id,
|
|
3642
|
-
status: row.status,
|
|
3643
|
-
activeVersionId: row.activeVersionId,
|
|
3644
|
-
authorId: row.authorId,
|
|
3645
|
-
metadata: row.metadata,
|
|
3646
|
-
createdAt: row.createdAt,
|
|
3647
|
-
createdAtZ: row.createdAtZ,
|
|
3648
|
-
updatedAt: row.updatedAt,
|
|
3649
|
-
updatedAtZ: row.updatedAtZ
|
|
3650
|
-
});
|
|
3651
|
-
if (row.version_id) {
|
|
3652
|
-
return {
|
|
3653
|
-
...agent,
|
|
3654
|
-
name: row.version_name,
|
|
3655
|
-
description: row.version_description,
|
|
3656
|
-
instructions: row.version_instructions,
|
|
3657
|
-
model: this.parseJson(row.version_model, "model"),
|
|
3658
|
-
tools: this.parseJson(row.version_tools, "tools"),
|
|
3659
|
-
defaultOptions: this.parseJson(row.version_defaultOptions, "defaultOptions"),
|
|
3660
|
-
workflows: this.parseJson(row.version_workflows, "workflows"),
|
|
3661
|
-
agents: this.parseJson(row.version_agents, "agents"),
|
|
3662
|
-
integrationTools: this.parseJson(row.version_integrationTools, "integrationTools"),
|
|
3663
|
-
inputProcessors: this.parseJson(row.version_inputProcessors, "inputProcessors"),
|
|
3664
|
-
outputProcessors: this.parseJson(row.version_outputProcessors, "outputProcessors"),
|
|
3665
|
-
memory: this.parseJson(row.version_memory, "memory"),
|
|
3666
|
-
scorers: this.parseJson(row.version_scorers, "scorers")
|
|
3667
|
-
};
|
|
3668
|
-
}
|
|
3669
|
-
return agent;
|
|
3670
|
-
});
|
|
3671
|
-
return {
|
|
3672
|
-
agents: resolvedAgents,
|
|
3673
|
-
total,
|
|
3674
|
-
page,
|
|
3675
|
-
perPage: perPageForResponse,
|
|
3676
|
-
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
3677
|
-
};
|
|
3678
|
-
} catch (error) {
|
|
3679
|
-
throw new MastraError(
|
|
3680
|
-
{
|
|
3681
|
-
id: createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "FAILED"),
|
|
3682
|
-
domain: ErrorDomain.STORAGE,
|
|
3683
|
-
category: ErrorCategory.THIRD_PARTY
|
|
3684
|
-
},
|
|
3685
|
-
error
|
|
3686
|
-
);
|
|
3687
|
-
}
|
|
3688
|
-
}
|
|
3689
3662
|
// ==========================================================================
|
|
3690
3663
|
// Agent Version Methods
|
|
3691
3664
|
// ==========================================================================
|
|
@@ -3709,7 +3682,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3709
3682
|
input.versionNumber,
|
|
3710
3683
|
input.name,
|
|
3711
3684
|
input.description ?? null,
|
|
3712
|
-
input.instructions,
|
|
3685
|
+
this.serializeInstructions(input.instructions),
|
|
3713
3686
|
JSON.stringify(input.model),
|
|
3714
3687
|
input.tools ? JSON.stringify(input.tools) : null,
|
|
3715
3688
|
input.defaultOptions ? JSON.stringify(input.defaultOptions) : null,
|
|
@@ -3731,6 +3704,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3731
3704
|
createdAt: now
|
|
3732
3705
|
};
|
|
3733
3706
|
} catch (error) {
|
|
3707
|
+
if (error instanceof MastraError) throw error;
|
|
3734
3708
|
throw new MastraError(
|
|
3735
3709
|
{
|
|
3736
3710
|
id: createStorageErrorId("PG", "CREATE_VERSION", "FAILED"),
|
|
@@ -3751,6 +3725,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3751
3725
|
}
|
|
3752
3726
|
return this.parseVersionRow(result);
|
|
3753
3727
|
} catch (error) {
|
|
3728
|
+
if (error instanceof MastraError) throw error;
|
|
3754
3729
|
throw new MastraError(
|
|
3755
3730
|
{
|
|
3756
3731
|
id: createStorageErrorId("PG", "GET_VERSION", "FAILED"),
|
|
@@ -3774,6 +3749,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3774
3749
|
}
|
|
3775
3750
|
return this.parseVersionRow(result);
|
|
3776
3751
|
} catch (error) {
|
|
3752
|
+
if (error instanceof MastraError) throw error;
|
|
3777
3753
|
throw new MastraError(
|
|
3778
3754
|
{
|
|
3779
3755
|
id: createStorageErrorId("PG", "GET_VERSION_BY_NUMBER", "FAILED"),
|
|
@@ -3797,6 +3773,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3797
3773
|
}
|
|
3798
3774
|
return this.parseVersionRow(result);
|
|
3799
3775
|
} catch (error) {
|
|
3776
|
+
if (error instanceof MastraError) throw error;
|
|
3800
3777
|
throw new MastraError(
|
|
3801
3778
|
{
|
|
3802
3779
|
id: createStorageErrorId("PG", "GET_LATEST_VERSION", "FAILED"),
|
|
@@ -3853,6 +3830,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3853
3830
|
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
3854
3831
|
};
|
|
3855
3832
|
} catch (error) {
|
|
3833
|
+
if (error instanceof MastraError) throw error;
|
|
3856
3834
|
throw new MastraError(
|
|
3857
3835
|
{
|
|
3858
3836
|
id: createStorageErrorId("PG", "LIST_VERSIONS", "FAILED"),
|
|
@@ -3869,6 +3847,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3869
3847
|
const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
|
|
3870
3848
|
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
3871
3849
|
} catch (error) {
|
|
3850
|
+
if (error instanceof MastraError) throw error;
|
|
3872
3851
|
throw new MastraError(
|
|
3873
3852
|
{
|
|
3874
3853
|
id: createStorageErrorId("PG", "DELETE_VERSION", "FAILED"),
|
|
@@ -3880,17 +3859,18 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3880
3859
|
);
|
|
3881
3860
|
}
|
|
3882
3861
|
}
|
|
3883
|
-
async
|
|
3862
|
+
async deleteVersionsByParentId(entityId) {
|
|
3884
3863
|
try {
|
|
3885
3864
|
const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
|
|
3886
|
-
await this.#db.client.none(`DELETE FROM ${tableName} WHERE "agentId" = $1`, [
|
|
3865
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE "agentId" = $1`, [entityId]);
|
|
3887
3866
|
} catch (error) {
|
|
3867
|
+
if (error instanceof MastraError) throw error;
|
|
3888
3868
|
throw new MastraError(
|
|
3889
3869
|
{
|
|
3890
3870
|
id: createStorageErrorId("PG", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
|
|
3891
3871
|
domain: ErrorDomain.STORAGE,
|
|
3892
3872
|
category: ErrorCategory.THIRD_PARTY,
|
|
3893
|
-
details: { agentId }
|
|
3873
|
+
details: { agentId: entityId }
|
|
3894
3874
|
},
|
|
3895
3875
|
error
|
|
3896
3876
|
);
|
|
@@ -3904,6 +3884,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3904
3884
|
]);
|
|
3905
3885
|
return parseInt(result.count, 10);
|
|
3906
3886
|
} catch (error) {
|
|
3887
|
+
if (error instanceof MastraError) throw error;
|
|
3907
3888
|
throw new MastraError(
|
|
3908
3889
|
{
|
|
3909
3890
|
id: createStorageErrorId("PG", "COUNT_VERSIONS", "FAILED"),
|
|
@@ -3918,6 +3899,19 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3918
3899
|
// ==========================================================================
|
|
3919
3900
|
// Private Helper Methods
|
|
3920
3901
|
// ==========================================================================
|
|
3902
|
+
serializeInstructions(instructions) {
|
|
3903
|
+
if (instructions == null) return void 0;
|
|
3904
|
+
return Array.isArray(instructions) ? JSON.stringify(instructions) : instructions;
|
|
3905
|
+
}
|
|
3906
|
+
deserializeInstructions(raw) {
|
|
3907
|
+
if (!raw) return "";
|
|
3908
|
+
try {
|
|
3909
|
+
const parsed = JSON.parse(raw);
|
|
3910
|
+
if (Array.isArray(parsed)) return parsed;
|
|
3911
|
+
} catch {
|
|
3912
|
+
}
|
|
3913
|
+
return raw;
|
|
3914
|
+
}
|
|
3921
3915
|
parseVersionRow(row) {
|
|
3922
3916
|
return {
|
|
3923
3917
|
id: row.id,
|
|
@@ -3925,7 +3919,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
|
|
|
3925
3919
|
versionNumber: row.versionNumber,
|
|
3926
3920
|
name: row.name,
|
|
3927
3921
|
description: row.description,
|
|
3928
|
-
instructions: row.instructions,
|
|
3922
|
+
instructions: this.deserializeInstructions(row.instructions),
|
|
3929
3923
|
model: this.parseJson(row.model, "model"),
|
|
3930
3924
|
tools: this.parseJson(row.tools, "tools"),
|
|
3931
3925
|
defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
|
|
@@ -3984,6 +3978,25 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
3984
3978
|
tableName: OM_TABLE,
|
|
3985
3979
|
schema: omSchema
|
|
3986
3980
|
});
|
|
3981
|
+
await this.#db.alterTable({
|
|
3982
|
+
tableName: OM_TABLE,
|
|
3983
|
+
schema: omSchema,
|
|
3984
|
+
ifNotExists: [
|
|
3985
|
+
"observedMessageIds",
|
|
3986
|
+
"observedTimezone",
|
|
3987
|
+
"bufferedObservations",
|
|
3988
|
+
"bufferedObservationTokens",
|
|
3989
|
+
"bufferedMessageIds",
|
|
3990
|
+
"bufferedReflection",
|
|
3991
|
+
"bufferedReflectionTokens",
|
|
3992
|
+
"bufferedReflectionInputTokens",
|
|
3993
|
+
"bufferedObservationChunks",
|
|
3994
|
+
"isBufferingObservation",
|
|
3995
|
+
"isBufferingReflection",
|
|
3996
|
+
"lastBufferedAtTokens",
|
|
3997
|
+
"lastBufferedAtTime"
|
|
3998
|
+
]
|
|
3999
|
+
});
|
|
3987
4000
|
}
|
|
3988
4001
|
await this.#db.alterTable({
|
|
3989
4002
|
tableName: TABLE_MESSAGES,
|
|
@@ -5179,12 +5192,26 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5179
5192
|
originType: row.originType || "initial",
|
|
5180
5193
|
generationCount: Number(row.generationCount || 0),
|
|
5181
5194
|
activeObservations: row.activeObservations || "",
|
|
5195
|
+
// Handle new chunk-based structure
|
|
5196
|
+
bufferedObservationChunks: row.bufferedObservationChunks ? typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks : void 0,
|
|
5197
|
+
// Deprecated fields (for backward compatibility)
|
|
5182
5198
|
bufferedObservations: row.activeObservationsPendingUpdate || void 0,
|
|
5199
|
+
bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
|
|
5200
|
+
bufferedMessageIds: void 0,
|
|
5201
|
+
// Use bufferedObservationChunks instead
|
|
5202
|
+
bufferedReflection: row.bufferedReflection || void 0,
|
|
5203
|
+
bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
|
|
5204
|
+
bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
|
|
5205
|
+
reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
|
|
5183
5206
|
totalTokensObserved: Number(row.totalTokensObserved || 0),
|
|
5184
5207
|
observationTokenCount: Number(row.observationTokenCount || 0),
|
|
5185
5208
|
pendingMessageTokens: Number(row.pendingMessageTokens || 0),
|
|
5186
5209
|
isReflecting: Boolean(row.isReflecting),
|
|
5187
5210
|
isObserving: Boolean(row.isObserving),
|
|
5211
|
+
isBufferingObservation: row.isBufferingObservation === true || row.isBufferingObservation === "true",
|
|
5212
|
+
isBufferingReflection: row.isBufferingReflection === true || row.isBufferingReflection === "true",
|
|
5213
|
+
lastBufferedAtTokens: typeof row.lastBufferedAtTokens === "number" ? row.lastBufferedAtTokens : parseInt(String(row.lastBufferedAtTokens ?? "0"), 10) || 0,
|
|
5214
|
+
lastBufferedAtTime: row.lastBufferedAtTime ? new Date(String(row.lastBufferedAtTime)) : null,
|
|
5188
5215
|
config: row.config ? typeof row.config === "string" ? JSON.parse(row.config) : row.config : {},
|
|
5189
5216
|
metadata: row.metadata ? typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata : void 0,
|
|
5190
5217
|
observedMessageIds: row.observedMessageIds ? typeof row.observedMessageIds === "string" ? JSON.parse(row.observedMessageIds) : row.observedMessageIds : void 0,
|
|
@@ -5262,6 +5289,10 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5262
5289
|
pendingMessageTokens: 0,
|
|
5263
5290
|
isReflecting: false,
|
|
5264
5291
|
isObserving: false,
|
|
5292
|
+
isBufferingObservation: false,
|
|
5293
|
+
isBufferingReflection: false,
|
|
5294
|
+
lastBufferedAtTokens: 0,
|
|
5295
|
+
lastBufferedAtTime: null,
|
|
5265
5296
|
config: input.config,
|
|
5266
5297
|
observedTimezone: input.observedTimezone
|
|
5267
5298
|
};
|
|
@@ -5276,8 +5307,9 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5276
5307
|
"activeObservations", "activeObservationsPendingUpdate",
|
|
5277
5308
|
"originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
|
|
5278
5309
|
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
5279
|
-
"isObserving", "isReflecting", "
|
|
5280
|
-
|
|
5310
|
+
"isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
|
|
5311
|
+
"observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
5312
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)`,
|
|
5281
5313
|
[
|
|
5282
5314
|
id,
|
|
5283
5315
|
lookupKey,
|
|
@@ -5302,6 +5334,14 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5302
5334
|
0,
|
|
5303
5335
|
false,
|
|
5304
5336
|
false,
|
|
5337
|
+
false,
|
|
5338
|
+
// isBufferingObservation
|
|
5339
|
+
false,
|
|
5340
|
+
// isBufferingReflection
|
|
5341
|
+
0,
|
|
5342
|
+
// lastBufferedAtTokens
|
|
5343
|
+
null,
|
|
5344
|
+
// lastBufferedAtTime
|
|
5305
5345
|
input.observedTimezone || null,
|
|
5306
5346
|
nowStr,
|
|
5307
5347
|
// createdAt
|
|
@@ -5405,6 +5445,10 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5405
5445
|
pendingMessageTokens: 0,
|
|
5406
5446
|
isReflecting: false,
|
|
5407
5447
|
isObserving: false,
|
|
5448
|
+
isBufferingObservation: false,
|
|
5449
|
+
isBufferingReflection: false,
|
|
5450
|
+
lastBufferedAtTokens: 0,
|
|
5451
|
+
lastBufferedAtTime: null,
|
|
5408
5452
|
config: input.currentRecord.config,
|
|
5409
5453
|
metadata: input.currentRecord.metadata,
|
|
5410
5454
|
observedTimezone: input.currentRecord.observedTimezone
|
|
@@ -5421,8 +5465,9 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5421
5465
|
"activeObservations", "activeObservationsPendingUpdate",
|
|
5422
5466
|
"originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
|
|
5423
5467
|
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
5424
|
-
"isObserving", "isReflecting", "
|
|
5425
|
-
|
|
5468
|
+
"isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
|
|
5469
|
+
"observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
5470
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)`,
|
|
5426
5471
|
[
|
|
5427
5472
|
id,
|
|
5428
5473
|
lookupKey,
|
|
@@ -5446,7 +5491,17 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5446
5491
|
record.totalTokensObserved,
|
|
5447
5492
|
record.observationTokenCount,
|
|
5448
5493
|
false,
|
|
5494
|
+
// isObserving
|
|
5449
5495
|
false,
|
|
5496
|
+
// isReflecting
|
|
5497
|
+
false,
|
|
5498
|
+
// isBufferingObservation
|
|
5499
|
+
false,
|
|
5500
|
+
// isBufferingReflection
|
|
5501
|
+
0,
|
|
5502
|
+
// lastBufferedAtTokens
|
|
5503
|
+
null,
|
|
5504
|
+
// lastBufferedAtTime
|
|
5450
5505
|
record.observedTimezone || null,
|
|
5451
5506
|
nowStr,
|
|
5452
5507
|
// createdAt
|
|
@@ -5541,6 +5596,82 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5541
5596
|
);
|
|
5542
5597
|
}
|
|
5543
5598
|
}
|
|
5599
|
+
async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
|
|
5600
|
+
try {
|
|
5601
|
+
const tableName = getTableName3({
|
|
5602
|
+
indexName: OM_TABLE,
|
|
5603
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5604
|
+
});
|
|
5605
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5606
|
+
let query;
|
|
5607
|
+
let values;
|
|
5608
|
+
if (lastBufferedAtTokens !== void 0) {
|
|
5609
|
+
query = `UPDATE ${tableName} SET "isBufferingObservation" = $1, "lastBufferedAtTokens" = $2, "updatedAt" = $3, "updatedAtZ" = $4 WHERE id = $5`;
|
|
5610
|
+
values = [isBuffering, lastBufferedAtTokens, nowStr, nowStr, id];
|
|
5611
|
+
} else {
|
|
5612
|
+
query = `UPDATE ${tableName} SET "isBufferingObservation" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`;
|
|
5613
|
+
values = [isBuffering, nowStr, nowStr, id];
|
|
5614
|
+
}
|
|
5615
|
+
const result = await this.#db.client.query(query, values);
|
|
5616
|
+
if (result.rowCount === 0) {
|
|
5617
|
+
throw new MastraError({
|
|
5618
|
+
id: createStorageErrorId("PG", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
|
|
5619
|
+
text: `Observational memory record not found: ${id}`,
|
|
5620
|
+
domain: ErrorDomain.STORAGE,
|
|
5621
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5622
|
+
details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
|
|
5623
|
+
});
|
|
5624
|
+
}
|
|
5625
|
+
} catch (error) {
|
|
5626
|
+
if (error instanceof MastraError) {
|
|
5627
|
+
throw error;
|
|
5628
|
+
}
|
|
5629
|
+
throw new MastraError(
|
|
5630
|
+
{
|
|
5631
|
+
id: createStorageErrorId("PG", "SET_BUFFERING_OBSERVATION_FLAG", "FAILED"),
|
|
5632
|
+
domain: ErrorDomain.STORAGE,
|
|
5633
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5634
|
+
details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
|
|
5635
|
+
},
|
|
5636
|
+
error
|
|
5637
|
+
);
|
|
5638
|
+
}
|
|
5639
|
+
}
|
|
5640
|
+
async setBufferingReflectionFlag(id, isBuffering) {
|
|
5641
|
+
try {
|
|
5642
|
+
const tableName = getTableName3({
|
|
5643
|
+
indexName: OM_TABLE,
|
|
5644
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5645
|
+
});
|
|
5646
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5647
|
+
const result = await this.#db.client.query(
|
|
5648
|
+
`UPDATE ${tableName} SET "isBufferingReflection" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`,
|
|
5649
|
+
[isBuffering, nowStr, nowStr, id]
|
|
5650
|
+
);
|
|
5651
|
+
if (result.rowCount === 0) {
|
|
5652
|
+
throw new MastraError({
|
|
5653
|
+
id: createStorageErrorId("PG", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
|
|
5654
|
+
text: `Observational memory record not found: ${id}`,
|
|
5655
|
+
domain: ErrorDomain.STORAGE,
|
|
5656
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5657
|
+
details: { id, isBuffering }
|
|
5658
|
+
});
|
|
5659
|
+
}
|
|
5660
|
+
} catch (error) {
|
|
5661
|
+
if (error instanceof MastraError) {
|
|
5662
|
+
throw error;
|
|
5663
|
+
}
|
|
5664
|
+
throw new MastraError(
|
|
5665
|
+
{
|
|
5666
|
+
id: createStorageErrorId("PG", "SET_BUFFERING_REFLECTION_FLAG", "FAILED"),
|
|
5667
|
+
domain: ErrorDomain.STORAGE,
|
|
5668
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5669
|
+
details: { id, isBuffering }
|
|
5670
|
+
},
|
|
5671
|
+
error
|
|
5672
|
+
);
|
|
5673
|
+
}
|
|
5674
|
+
}
|
|
5544
5675
|
async clearObservationalMemory(threadId, resourceId) {
|
|
5545
5676
|
try {
|
|
5546
5677
|
const lookupKey = this.getOMKey(threadId, resourceId);
|
|
@@ -5600,71 +5731,385 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
|
|
|
5600
5731
|
);
|
|
5601
5732
|
}
|
|
5602
5733
|
}
|
|
5603
|
-
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
|
|
5609
|
-
|
|
5610
|
-
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
|
|
5734
|
+
// ============================================
|
|
5735
|
+
// Async Buffering Methods
|
|
5736
|
+
// ============================================
|
|
5737
|
+
async updateBufferedObservations(input) {
|
|
5738
|
+
try {
|
|
5739
|
+
const tableName = getTableName3({
|
|
5740
|
+
indexName: OM_TABLE,
|
|
5741
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5742
|
+
});
|
|
5743
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5744
|
+
const newChunk = {
|
|
5745
|
+
id: `ombuf-${randomUUID()}`,
|
|
5746
|
+
cycleId: input.chunk.cycleId,
|
|
5747
|
+
observations: input.chunk.observations,
|
|
5748
|
+
tokenCount: input.chunk.tokenCount,
|
|
5749
|
+
messageIds: input.chunk.messageIds,
|
|
5750
|
+
messageTokens: input.chunk.messageTokens,
|
|
5751
|
+
lastObservedAt: input.chunk.lastObservedAt,
|
|
5752
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
5753
|
+
suggestedContinuation: input.chunk.suggestedContinuation,
|
|
5754
|
+
currentTask: input.chunk.currentTask
|
|
5755
|
+
};
|
|
5756
|
+
const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
|
|
5757
|
+
const result = await this.#db.client.query(
|
|
5758
|
+
`UPDATE ${tableName} SET
|
|
5759
|
+
"bufferedObservationChunks" = COALESCE("bufferedObservationChunks", '[]'::jsonb) || $1::jsonb,
|
|
5760
|
+
"lastBufferedAtTime" = COALESCE($2, "lastBufferedAtTime"),
|
|
5761
|
+
"updatedAt" = $3,
|
|
5762
|
+
"updatedAtZ" = $4
|
|
5763
|
+
WHERE id = $5`,
|
|
5764
|
+
[JSON.stringify([newChunk]), lastBufferedAtTime, nowStr, nowStr, input.id]
|
|
5765
|
+
);
|
|
5766
|
+
if (result.rowCount === 0) {
|
|
5767
|
+
throw new MastraError({
|
|
5768
|
+
id: createStorageErrorId("PG", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
|
|
5769
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
5770
|
+
domain: ErrorDomain.STORAGE,
|
|
5771
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5772
|
+
details: { id: input.id }
|
|
5773
|
+
});
|
|
5774
|
+
}
|
|
5775
|
+
} catch (error) {
|
|
5776
|
+
if (error instanceof MastraError) {
|
|
5777
|
+
throw error;
|
|
5778
|
+
}
|
|
5779
|
+
throw new MastraError(
|
|
5780
|
+
{
|
|
5781
|
+
id: createStorageErrorId("PG", "UPDATE_BUFFERED_OBSERVATIONS", "FAILED"),
|
|
5782
|
+
domain: ErrorDomain.STORAGE,
|
|
5783
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5784
|
+
details: { id: input.id }
|
|
5785
|
+
},
|
|
5786
|
+
error
|
|
5787
|
+
);
|
|
5788
|
+
}
|
|
5623
5789
|
}
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5634
|
-
|
|
5635
|
-
|
|
5636
|
-
|
|
5637
|
-
|
|
5638
|
-
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
|
|
5645
|
-
|
|
5646
|
-
|
|
5647
|
-
|
|
5648
|
-
|
|
5649
|
-
}
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5790
|
+
async swapBufferedToActive(input) {
|
|
5791
|
+
try {
|
|
5792
|
+
const tableName = getTableName3({
|
|
5793
|
+
indexName: OM_TABLE,
|
|
5794
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5795
|
+
});
|
|
5796
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5797
|
+
const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.id]);
|
|
5798
|
+
if (!record) {
|
|
5799
|
+
throw new MastraError({
|
|
5800
|
+
id: createStorageErrorId("PG", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
|
|
5801
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
5802
|
+
domain: ErrorDomain.STORAGE,
|
|
5803
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5804
|
+
details: { id: input.id }
|
|
5805
|
+
});
|
|
5806
|
+
}
|
|
5807
|
+
let chunks = [];
|
|
5808
|
+
if (record.bufferedObservationChunks) {
|
|
5809
|
+
try {
|
|
5810
|
+
const parsed = typeof record.bufferedObservationChunks === "string" ? JSON.parse(record.bufferedObservationChunks) : record.bufferedObservationChunks;
|
|
5811
|
+
chunks = Array.isArray(parsed) ? parsed : [];
|
|
5812
|
+
} catch {
|
|
5813
|
+
chunks = [];
|
|
5814
|
+
}
|
|
5815
|
+
}
|
|
5816
|
+
if (chunks.length === 0) {
|
|
5817
|
+
return {
|
|
5818
|
+
chunksActivated: 0,
|
|
5819
|
+
messageTokensActivated: 0,
|
|
5820
|
+
observationTokensActivated: 0,
|
|
5821
|
+
messagesActivated: 0,
|
|
5822
|
+
activatedCycleIds: [],
|
|
5823
|
+
activatedMessageIds: []
|
|
5824
|
+
};
|
|
5825
|
+
}
|
|
5826
|
+
const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
|
|
5827
|
+
const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
|
|
5828
|
+
let cumulativeMessageTokens = 0;
|
|
5829
|
+
let chunksToActivate = 0;
|
|
5830
|
+
let bestBoundary = 0;
|
|
5831
|
+
let bestBoundaryMessageTokens = 0;
|
|
5832
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
5833
|
+
cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
|
|
5834
|
+
const boundary = i + 1;
|
|
5835
|
+
const isUnder = cumulativeMessageTokens <= targetMessageTokens;
|
|
5836
|
+
const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
|
|
5837
|
+
if (bestBoundary === 0) {
|
|
5838
|
+
bestBoundary = boundary;
|
|
5839
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
5840
|
+
} else if (isUnder && !bestIsUnder) {
|
|
5841
|
+
bestBoundary = boundary;
|
|
5842
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
5843
|
+
} else if (isUnder && bestIsUnder) {
|
|
5844
|
+
if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
|
|
5845
|
+
bestBoundary = boundary;
|
|
5846
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
5847
|
+
}
|
|
5848
|
+
} else if (!isUnder && !bestIsUnder) {
|
|
5849
|
+
if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
|
|
5850
|
+
bestBoundary = boundary;
|
|
5851
|
+
bestBoundaryMessageTokens = cumulativeMessageTokens;
|
|
5852
|
+
}
|
|
5853
|
+
}
|
|
5854
|
+
}
|
|
5855
|
+
chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
|
|
5856
|
+
const activatedChunks = chunks.slice(0, chunksToActivate);
|
|
5857
|
+
const remainingChunks = chunks.slice(chunksToActivate);
|
|
5858
|
+
const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
|
|
5859
|
+
const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
|
|
5860
|
+
const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
|
|
5861
|
+
const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
|
|
5862
|
+
const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
|
|
5863
|
+
const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
|
|
5864
|
+
const latestChunk = activatedChunks[activatedChunks.length - 1];
|
|
5865
|
+
const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
|
|
5866
|
+
const lastObservedAtStr = lastObservedAt.toISOString();
|
|
5867
|
+
await this.#db.client.query(
|
|
5868
|
+
`UPDATE ${tableName} SET
|
|
5869
|
+
"activeObservations" = CASE
|
|
5870
|
+
WHEN "activeObservations" IS NOT NULL AND "activeObservations" != ''
|
|
5871
|
+
THEN "activeObservations" || E'\\n\\n' || $1
|
|
5872
|
+
ELSE $1
|
|
5873
|
+
END,
|
|
5874
|
+
"observationTokenCount" = COALESCE("observationTokenCount", 0) + $2,
|
|
5875
|
+
"pendingMessageTokens" = GREATEST(0, COALESCE("pendingMessageTokens", 0) - $3),
|
|
5876
|
+
"bufferedObservationChunks" = $4,
|
|
5877
|
+
"lastObservedAt" = $5,
|
|
5878
|
+
"lastObservedAtZ" = $6,
|
|
5879
|
+
"updatedAt" = $7,
|
|
5880
|
+
"updatedAtZ" = $8
|
|
5881
|
+
WHERE id = $9`,
|
|
5882
|
+
[
|
|
5883
|
+
activatedContent,
|
|
5884
|
+
activatedTokens,
|
|
5885
|
+
activatedMessageTokens,
|
|
5886
|
+
remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
|
|
5887
|
+
lastObservedAtStr,
|
|
5888
|
+
lastObservedAtStr,
|
|
5889
|
+
nowStr,
|
|
5890
|
+
nowStr,
|
|
5891
|
+
input.id
|
|
5892
|
+
]
|
|
5893
|
+
);
|
|
5894
|
+
return {
|
|
5895
|
+
chunksActivated: activatedChunks.length,
|
|
5896
|
+
messageTokensActivated: activatedMessageTokens,
|
|
5897
|
+
observationTokensActivated: activatedTokens,
|
|
5898
|
+
messagesActivated: activatedMessageCount,
|
|
5899
|
+
activatedCycleIds,
|
|
5900
|
+
activatedMessageIds,
|
|
5901
|
+
observations: activatedContent,
|
|
5902
|
+
perChunk: activatedChunks.map((c) => ({
|
|
5903
|
+
cycleId: c.cycleId ?? "",
|
|
5904
|
+
messageTokens: c.messageTokens ?? 0,
|
|
5905
|
+
observationTokens: c.tokenCount,
|
|
5906
|
+
messageCount: c.messageIds.length,
|
|
5907
|
+
observations: c.observations
|
|
5908
|
+
}))
|
|
5909
|
+
};
|
|
5910
|
+
} catch (error) {
|
|
5911
|
+
if (error instanceof MastraError) {
|
|
5912
|
+
throw error;
|
|
5913
|
+
}
|
|
5914
|
+
throw new MastraError(
|
|
5915
|
+
{
|
|
5916
|
+
id: createStorageErrorId("PG", "SWAP_BUFFERED_TO_ACTIVE", "FAILED"),
|
|
5917
|
+
domain: ErrorDomain.STORAGE,
|
|
5918
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5919
|
+
details: { id: input.id }
|
|
5920
|
+
},
|
|
5921
|
+
error
|
|
5922
|
+
);
|
|
5923
|
+
}
|
|
5924
|
+
}
|
|
5925
|
+
async updateBufferedReflection(input) {
|
|
5926
|
+
try {
|
|
5927
|
+
const tableName = getTableName3({
|
|
5928
|
+
indexName: OM_TABLE,
|
|
5929
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5930
|
+
});
|
|
5931
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5932
|
+
const result = await this.#db.client.query(
|
|
5933
|
+
`UPDATE ${tableName} SET
|
|
5934
|
+
"bufferedReflection" = CASE
|
|
5935
|
+
WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
|
|
5936
|
+
THEN "bufferedReflection" || E'\\n\\n' || $1
|
|
5937
|
+
ELSE $1
|
|
5938
|
+
END,
|
|
5939
|
+
"bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + $2,
|
|
5940
|
+
"bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + $3,
|
|
5941
|
+
"reflectedObservationLineCount" = $4,
|
|
5942
|
+
"updatedAt" = $5,
|
|
5943
|
+
"updatedAtZ" = $6
|
|
5944
|
+
WHERE id = $7`,
|
|
5945
|
+
[
|
|
5946
|
+
input.reflection,
|
|
5947
|
+
input.tokenCount,
|
|
5948
|
+
input.inputTokenCount,
|
|
5949
|
+
input.reflectedObservationLineCount,
|
|
5950
|
+
nowStr,
|
|
5951
|
+
nowStr,
|
|
5952
|
+
input.id
|
|
5953
|
+
]
|
|
5954
|
+
);
|
|
5955
|
+
if (result.rowCount === 0) {
|
|
5956
|
+
throw new MastraError({
|
|
5957
|
+
id: createStorageErrorId("PG", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
|
|
5958
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
5959
|
+
domain: ErrorDomain.STORAGE,
|
|
5960
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5961
|
+
details: { id: input.id }
|
|
5962
|
+
});
|
|
5963
|
+
}
|
|
5964
|
+
} catch (error) {
|
|
5965
|
+
if (error instanceof MastraError) {
|
|
5966
|
+
throw error;
|
|
5967
|
+
}
|
|
5968
|
+
throw new MastraError(
|
|
5969
|
+
{
|
|
5970
|
+
id: createStorageErrorId("PG", "UPDATE_BUFFERED_REFLECTION", "FAILED"),
|
|
5971
|
+
domain: ErrorDomain.STORAGE,
|
|
5972
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5973
|
+
details: { id: input.id }
|
|
5974
|
+
},
|
|
5975
|
+
error
|
|
5976
|
+
);
|
|
5977
|
+
}
|
|
5978
|
+
}
|
|
5979
|
+
async swapBufferedReflectionToActive(input) {
|
|
5980
|
+
try {
|
|
5981
|
+
const tableName = getTableName3({
|
|
5982
|
+
indexName: OM_TABLE,
|
|
5983
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5984
|
+
});
|
|
5985
|
+
const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [
|
|
5986
|
+
input.currentRecord.id
|
|
5987
|
+
]);
|
|
5988
|
+
if (!record) {
|
|
5989
|
+
throw new MastraError({
|
|
5990
|
+
id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
|
|
5991
|
+
text: `Observational memory record not found: ${input.currentRecord.id}`,
|
|
5992
|
+
domain: ErrorDomain.STORAGE,
|
|
5993
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
5994
|
+
details: { id: input.currentRecord.id }
|
|
5995
|
+
});
|
|
5996
|
+
}
|
|
5997
|
+
const bufferedReflection = record.bufferedReflection || "";
|
|
5998
|
+
const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
|
|
5999
|
+
if (!bufferedReflection) {
|
|
6000
|
+
throw new MastraError({
|
|
6001
|
+
id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
|
|
6002
|
+
text: "No buffered reflection to swap",
|
|
6003
|
+
domain: ErrorDomain.STORAGE,
|
|
6004
|
+
category: ErrorCategory.USER,
|
|
6005
|
+
details: { id: input.currentRecord.id }
|
|
6006
|
+
});
|
|
6007
|
+
}
|
|
6008
|
+
const currentObservations = record.activeObservations || "";
|
|
6009
|
+
const allLines = currentObservations.split("\n");
|
|
6010
|
+
const unreflectedLines = allLines.slice(reflectedLineCount);
|
|
6011
|
+
const unreflectedContent = unreflectedLines.join("\n").trim();
|
|
6012
|
+
const newObservations = unreflectedContent ? `${bufferedReflection}
|
|
6013
|
+
|
|
6014
|
+
${unreflectedContent}` : bufferedReflection;
|
|
6015
|
+
const newRecord = await this.createReflectionGeneration({
|
|
6016
|
+
currentRecord: input.currentRecord,
|
|
6017
|
+
reflection: newObservations,
|
|
6018
|
+
tokenCount: input.tokenCount
|
|
6019
|
+
});
|
|
6020
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
6021
|
+
await this.#db.client.query(
|
|
6022
|
+
`UPDATE ${tableName} SET
|
|
6023
|
+
"bufferedReflection" = NULL,
|
|
6024
|
+
"bufferedReflectionTokens" = NULL,
|
|
6025
|
+
"bufferedReflectionInputTokens" = NULL,
|
|
6026
|
+
"reflectedObservationLineCount" = NULL,
|
|
6027
|
+
"updatedAt" = $1,
|
|
6028
|
+
"updatedAtZ" = $2
|
|
6029
|
+
WHERE id = $3`,
|
|
6030
|
+
[nowStr, nowStr, input.currentRecord.id]
|
|
6031
|
+
);
|
|
6032
|
+
return newRecord;
|
|
6033
|
+
} catch (error) {
|
|
6034
|
+
if (error instanceof MastraError) {
|
|
6035
|
+
throw error;
|
|
6036
|
+
}
|
|
6037
|
+
throw new MastraError(
|
|
6038
|
+
{
|
|
6039
|
+
id: createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "FAILED"),
|
|
6040
|
+
domain: ErrorDomain.STORAGE,
|
|
6041
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
6042
|
+
details: { id: input.currentRecord.id }
|
|
6043
|
+
},
|
|
6044
|
+
error
|
|
6045
|
+
);
|
|
6046
|
+
}
|
|
6047
|
+
}
|
|
6048
|
+
};
|
|
6049
|
+
var ObservabilityPG = class _ObservabilityPG extends ObservabilityStorage {
|
|
6050
|
+
#db;
|
|
6051
|
+
#schema;
|
|
6052
|
+
#skipDefaultIndexes;
|
|
6053
|
+
#indexes;
|
|
6054
|
+
/** Tables managed by this domain */
|
|
6055
|
+
static MANAGED_TABLES = [TABLE_SPANS];
|
|
6056
|
+
constructor(config) {
|
|
6057
|
+
super();
|
|
6058
|
+
const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
|
|
6059
|
+
this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
|
|
6060
|
+
this.#schema = schemaName || "public";
|
|
6061
|
+
this.#skipDefaultIndexes = skipDefaultIndexes;
|
|
6062
|
+
this.#indexes = indexes?.filter((idx) => _ObservabilityPG.MANAGED_TABLES.includes(idx.table));
|
|
6063
|
+
}
|
|
6064
|
+
async init() {
|
|
6065
|
+
await this.#db.createTable({ tableName: TABLE_SPANS, schema: TABLE_SCHEMAS[TABLE_SPANS] });
|
|
6066
|
+
await this.createDefaultIndexes();
|
|
6067
|
+
await this.createCustomIndexes();
|
|
6068
|
+
}
|
|
6069
|
+
/**
|
|
6070
|
+
* Returns default index definitions for the observability domain tables.
|
|
6071
|
+
*/
|
|
6072
|
+
getDefaultIndexDefinitions() {
|
|
6073
|
+
const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
|
|
6074
|
+
return [
|
|
6075
|
+
{
|
|
6076
|
+
name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
|
|
6077
|
+
table: TABLE_SPANS,
|
|
6078
|
+
columns: ["traceId", "startedAt DESC"]
|
|
6079
|
+
},
|
|
6080
|
+
{
|
|
6081
|
+
name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
|
|
6082
|
+
table: TABLE_SPANS,
|
|
6083
|
+
columns: ["parentSpanId", "startedAt DESC"]
|
|
6084
|
+
},
|
|
6085
|
+
{
|
|
6086
|
+
name: `${schemaPrefix}mastra_ai_spans_name_idx`,
|
|
6087
|
+
table: TABLE_SPANS,
|
|
6088
|
+
columns: ["name"]
|
|
6089
|
+
},
|
|
6090
|
+
{
|
|
6091
|
+
name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
|
|
6092
|
+
table: TABLE_SPANS,
|
|
6093
|
+
columns: ["spanType", "startedAt DESC"]
|
|
6094
|
+
},
|
|
6095
|
+
// Root spans partial index - every listTraces query filters parentSpanId IS NULL
|
|
6096
|
+
{
|
|
6097
|
+
name: `${schemaPrefix}mastra_ai_spans_root_spans_idx`,
|
|
6098
|
+
table: TABLE_SPANS,
|
|
6099
|
+
columns: ["startedAt DESC"],
|
|
6100
|
+
where: '"parentSpanId" IS NULL'
|
|
6101
|
+
},
|
|
6102
|
+
// Entity identification indexes - common filtering patterns
|
|
6103
|
+
{
|
|
6104
|
+
name: `${schemaPrefix}mastra_ai_spans_entitytype_entityid_idx`,
|
|
6105
|
+
table: TABLE_SPANS,
|
|
6106
|
+
columns: ["entityType", "entityId"]
|
|
6107
|
+
},
|
|
6108
|
+
{
|
|
6109
|
+
name: `${schemaPrefix}mastra_ai_spans_entitytype_entityname_idx`,
|
|
6110
|
+
table: TABLE_SPANS,
|
|
6111
|
+
columns: ["entityType", "entityName"]
|
|
6112
|
+
},
|
|
5668
6113
|
// Multi-tenant filtering - organizationId + userId
|
|
5669
6114
|
{
|
|
5670
6115
|
name: `${schemaPrefix}mastra_ai_spans_orgid_userid_idx`,
|
|
@@ -6215,6 +6660,1338 @@ var ObservabilityPG = class _ObservabilityPG extends ObservabilityStorage {
|
|
|
6215
6660
|
}
|
|
6216
6661
|
}
|
|
6217
6662
|
};
|
|
6663
|
+
var SNAPSHOT_FIELDS = ["name", "description", "content", "rules"];
|
|
6664
|
+
var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
|
|
6665
|
+
#db;
|
|
6666
|
+
#schema;
|
|
6667
|
+
#skipDefaultIndexes;
|
|
6668
|
+
#indexes;
|
|
6669
|
+
static MANAGED_TABLES = [TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS];
|
|
6670
|
+
constructor(config) {
|
|
6671
|
+
super();
|
|
6672
|
+
const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
|
|
6673
|
+
this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
|
|
6674
|
+
this.#schema = schemaName || "public";
|
|
6675
|
+
this.#skipDefaultIndexes = skipDefaultIndexes;
|
|
6676
|
+
this.#indexes = indexes?.filter((idx) => _PromptBlocksPG.MANAGED_TABLES.includes(idx.table));
|
|
6677
|
+
}
|
|
6678
|
+
getDefaultIndexDefinitions() {
|
|
6679
|
+
return [
|
|
6680
|
+
{
|
|
6681
|
+
name: "idx_prompt_block_versions_block_version",
|
|
6682
|
+
table: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
6683
|
+
columns: ["blockId", "versionNumber"],
|
|
6684
|
+
unique: true
|
|
6685
|
+
}
|
|
6686
|
+
];
|
|
6687
|
+
}
|
|
6688
|
+
async createDefaultIndexes() {
|
|
6689
|
+
if (this.#skipDefaultIndexes) {
|
|
6690
|
+
return;
|
|
6691
|
+
}
|
|
6692
|
+
for (const indexDef of this.getDefaultIndexDefinitions()) {
|
|
6693
|
+
try {
|
|
6694
|
+
await this.#db.createIndex(indexDef);
|
|
6695
|
+
} catch {
|
|
6696
|
+
}
|
|
6697
|
+
}
|
|
6698
|
+
}
|
|
6699
|
+
async init() {
|
|
6700
|
+
await this.#db.createTable({ tableName: TABLE_PROMPT_BLOCKS, schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCKS] });
|
|
6701
|
+
await this.#db.createTable({
|
|
6702
|
+
tableName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
6703
|
+
schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCK_VERSIONS]
|
|
6704
|
+
});
|
|
6705
|
+
await this.createDefaultIndexes();
|
|
6706
|
+
await this.createCustomIndexes();
|
|
6707
|
+
}
|
|
6708
|
+
async createCustomIndexes() {
|
|
6709
|
+
if (!this.#indexes || this.#indexes.length === 0) {
|
|
6710
|
+
return;
|
|
6711
|
+
}
|
|
6712
|
+
for (const indexDef of this.#indexes) {
|
|
6713
|
+
try {
|
|
6714
|
+
await this.#db.createIndex(indexDef);
|
|
6715
|
+
} catch (error) {
|
|
6716
|
+
this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
|
|
6717
|
+
}
|
|
6718
|
+
}
|
|
6719
|
+
}
|
|
6720
|
+
async dangerouslyClearAll() {
|
|
6721
|
+
await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCK_VERSIONS });
|
|
6722
|
+
await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCKS });
|
|
6723
|
+
}
|
|
6724
|
+
// ==========================================================================
|
|
6725
|
+
// Prompt Block CRUD Methods
|
|
6726
|
+
// ==========================================================================
|
|
6727
|
+
async getById(id) {
|
|
6728
|
+
try {
|
|
6729
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6730
|
+
const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
|
|
6731
|
+
if (!result) {
|
|
6732
|
+
return null;
|
|
6733
|
+
}
|
|
6734
|
+
return this.parseBlockRow(result);
|
|
6735
|
+
} catch (error) {
|
|
6736
|
+
if (error instanceof MastraError) throw error;
|
|
6737
|
+
throw new MastraError(
|
|
6738
|
+
{
|
|
6739
|
+
id: createStorageErrorId("PG", "GET_PROMPT_BLOCK_BY_ID", "FAILED"),
|
|
6740
|
+
domain: ErrorDomain.STORAGE,
|
|
6741
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
6742
|
+
details: { blockId: id }
|
|
6743
|
+
},
|
|
6744
|
+
error
|
|
6745
|
+
);
|
|
6746
|
+
}
|
|
6747
|
+
}
|
|
6748
|
+
async create(input) {
|
|
6749
|
+
const { promptBlock } = input;
|
|
6750
|
+
try {
|
|
6751
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6752
|
+
const now = /* @__PURE__ */ new Date();
|
|
6753
|
+
const nowIso = now.toISOString();
|
|
6754
|
+
await this.#db.client.none(
|
|
6755
|
+
`INSERT INTO ${tableName} (
|
|
6756
|
+
id, status, "activeVersionId", "authorId", metadata,
|
|
6757
|
+
"createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
6758
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
|
6759
|
+
[
|
|
6760
|
+
promptBlock.id,
|
|
6761
|
+
"draft",
|
|
6762
|
+
null,
|
|
6763
|
+
promptBlock.authorId ?? null,
|
|
6764
|
+
promptBlock.metadata ? JSON.stringify(promptBlock.metadata) : null,
|
|
6765
|
+
nowIso,
|
|
6766
|
+
nowIso,
|
|
6767
|
+
nowIso,
|
|
6768
|
+
nowIso
|
|
6769
|
+
]
|
|
6770
|
+
);
|
|
6771
|
+
const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = promptBlock;
|
|
6772
|
+
const versionId = crypto.randomUUID();
|
|
6773
|
+
await this.createVersion({
|
|
6774
|
+
id: versionId,
|
|
6775
|
+
blockId: promptBlock.id,
|
|
6776
|
+
versionNumber: 1,
|
|
6777
|
+
...snapshotConfig,
|
|
6778
|
+
changedFields: [...SNAPSHOT_FIELDS],
|
|
6779
|
+
changeMessage: "Initial version"
|
|
6780
|
+
});
|
|
6781
|
+
return {
|
|
6782
|
+
id: promptBlock.id,
|
|
6783
|
+
status: "draft",
|
|
6784
|
+
activeVersionId: void 0,
|
|
6785
|
+
authorId: promptBlock.authorId,
|
|
6786
|
+
metadata: promptBlock.metadata,
|
|
6787
|
+
createdAt: now,
|
|
6788
|
+
updatedAt: now
|
|
6789
|
+
};
|
|
6790
|
+
} catch (error) {
|
|
6791
|
+
if (error instanceof MastraError) throw error;
|
|
6792
|
+
try {
|
|
6793
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6794
|
+
await this.#db.client.none(
|
|
6795
|
+
`DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
|
|
6796
|
+
[promptBlock.id]
|
|
6797
|
+
);
|
|
6798
|
+
} catch {
|
|
6799
|
+
}
|
|
6800
|
+
throw new MastraError(
|
|
6801
|
+
{
|
|
6802
|
+
id: createStorageErrorId("PG", "CREATE_PROMPT_BLOCK", "FAILED"),
|
|
6803
|
+
domain: ErrorDomain.STORAGE,
|
|
6804
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
6805
|
+
details: { blockId: promptBlock.id }
|
|
6806
|
+
},
|
|
6807
|
+
error
|
|
6808
|
+
);
|
|
6809
|
+
}
|
|
6810
|
+
}
|
|
6811
|
+
async update(input) {
|
|
6812
|
+
const { id, ...updates } = input;
|
|
6813
|
+
try {
|
|
6814
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6815
|
+
const existingBlock = await this.getById(id);
|
|
6816
|
+
if (!existingBlock) {
|
|
6817
|
+
throw new MastraError({
|
|
6818
|
+
id: createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
|
|
6819
|
+
domain: ErrorDomain.STORAGE,
|
|
6820
|
+
category: ErrorCategory.USER,
|
|
6821
|
+
text: `Prompt block ${id} not found`,
|
|
6822
|
+
details: { blockId: id }
|
|
6823
|
+
});
|
|
6824
|
+
}
|
|
6825
|
+
const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
|
|
6826
|
+
let versionCreated = false;
|
|
6827
|
+
const hasConfigUpdate = SNAPSHOT_FIELDS.some((field) => field in configFields);
|
|
6828
|
+
if (hasConfigUpdate) {
|
|
6829
|
+
const latestVersion = await this.getLatestVersion(id);
|
|
6830
|
+
if (!latestVersion) {
|
|
6831
|
+
throw new MastraError({
|
|
6832
|
+
id: createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NO_VERSIONS"),
|
|
6833
|
+
domain: ErrorDomain.STORAGE,
|
|
6834
|
+
category: ErrorCategory.SYSTEM,
|
|
6835
|
+
text: `No versions found for prompt block ${id}`,
|
|
6836
|
+
details: { blockId: id }
|
|
6837
|
+
});
|
|
6838
|
+
}
|
|
6839
|
+
const {
|
|
6840
|
+
id: _versionId,
|
|
6841
|
+
blockId: _blockId,
|
|
6842
|
+
versionNumber: _versionNumber,
|
|
6843
|
+
changedFields: _changedFields,
|
|
6844
|
+
changeMessage: _changeMessage,
|
|
6845
|
+
createdAt: _createdAt,
|
|
6846
|
+
...latestConfig
|
|
6847
|
+
} = latestVersion;
|
|
6848
|
+
const newConfig = { ...latestConfig, ...configFields };
|
|
6849
|
+
const changedFields = SNAPSHOT_FIELDS.filter(
|
|
6850
|
+
(field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
|
|
6851
|
+
);
|
|
6852
|
+
if (changedFields.length > 0) {
|
|
6853
|
+
versionCreated = true;
|
|
6854
|
+
const newVersionId = crypto.randomUUID();
|
|
6855
|
+
await this.createVersion({
|
|
6856
|
+
id: newVersionId,
|
|
6857
|
+
blockId: id,
|
|
6858
|
+
versionNumber: latestVersion.versionNumber + 1,
|
|
6859
|
+
...newConfig,
|
|
6860
|
+
changedFields: [...changedFields],
|
|
6861
|
+
changeMessage: `Updated ${changedFields.join(", ")}`
|
|
6862
|
+
});
|
|
6863
|
+
}
|
|
6864
|
+
}
|
|
6865
|
+
const setClauses = [];
|
|
6866
|
+
const values = [];
|
|
6867
|
+
let paramIndex = 1;
|
|
6868
|
+
if (authorId !== void 0) {
|
|
6869
|
+
setClauses.push(`"authorId" = $${paramIndex++}`);
|
|
6870
|
+
values.push(authorId);
|
|
6871
|
+
}
|
|
6872
|
+
if (activeVersionId !== void 0) {
|
|
6873
|
+
setClauses.push(`"activeVersionId" = $${paramIndex++}`);
|
|
6874
|
+
values.push(activeVersionId);
|
|
6875
|
+
if (status === void 0) {
|
|
6876
|
+
setClauses.push(`status = $${paramIndex++}`);
|
|
6877
|
+
values.push("published");
|
|
6878
|
+
}
|
|
6879
|
+
}
|
|
6880
|
+
if (status !== void 0) {
|
|
6881
|
+
setClauses.push(`status = $${paramIndex++}`);
|
|
6882
|
+
values.push(status);
|
|
6883
|
+
}
|
|
6884
|
+
if (metadata !== void 0) {
|
|
6885
|
+
const mergedMetadata = { ...existingBlock.metadata || {}, ...metadata };
|
|
6886
|
+
setClauses.push(`metadata = $${paramIndex++}`);
|
|
6887
|
+
values.push(JSON.stringify(mergedMetadata));
|
|
6888
|
+
}
|
|
6889
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
6890
|
+
setClauses.push(`"updatedAt" = $${paramIndex++}`);
|
|
6891
|
+
values.push(now);
|
|
6892
|
+
setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
|
|
6893
|
+
values.push(now);
|
|
6894
|
+
values.push(id);
|
|
6895
|
+
if (setClauses.length > 2 || versionCreated) {
|
|
6896
|
+
await this.#db.client.none(
|
|
6897
|
+
`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`,
|
|
6898
|
+
values
|
|
6899
|
+
);
|
|
6900
|
+
}
|
|
6901
|
+
const updatedBlock = await this.getById(id);
|
|
6902
|
+
if (!updatedBlock) {
|
|
6903
|
+
throw new MastraError({
|
|
6904
|
+
id: createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
|
|
6905
|
+
domain: ErrorDomain.STORAGE,
|
|
6906
|
+
category: ErrorCategory.SYSTEM,
|
|
6907
|
+
text: `Prompt block ${id} not found after update`,
|
|
6908
|
+
details: { blockId: id }
|
|
6909
|
+
});
|
|
6910
|
+
}
|
|
6911
|
+
return updatedBlock;
|
|
6912
|
+
} catch (error) {
|
|
6913
|
+
if (error instanceof MastraError) throw error;
|
|
6914
|
+
throw new MastraError(
|
|
6915
|
+
{
|
|
6916
|
+
id: createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "FAILED"),
|
|
6917
|
+
domain: ErrorDomain.STORAGE,
|
|
6918
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
6919
|
+
details: { blockId: id }
|
|
6920
|
+
},
|
|
6921
|
+
error
|
|
6922
|
+
);
|
|
6923
|
+
}
|
|
6924
|
+
}
|
|
6925
|
+
async delete(id) {
|
|
6926
|
+
try {
|
|
6927
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6928
|
+
await this.deleteVersionsByParentId(id);
|
|
6929
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
6930
|
+
} catch (error) {
|
|
6931
|
+
if (error instanceof MastraError) throw error;
|
|
6932
|
+
throw new MastraError(
|
|
6933
|
+
{
|
|
6934
|
+
id: createStorageErrorId("PG", "DELETE_PROMPT_BLOCK", "FAILED"),
|
|
6935
|
+
domain: ErrorDomain.STORAGE,
|
|
6936
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
6937
|
+
details: { blockId: id }
|
|
6938
|
+
},
|
|
6939
|
+
error
|
|
6940
|
+
);
|
|
6941
|
+
}
|
|
6942
|
+
}
|
|
6943
|
+
async list(args) {
|
|
6944
|
+
const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
|
|
6945
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
6946
|
+
if (page < 0) {
|
|
6947
|
+
throw new MastraError(
|
|
6948
|
+
{
|
|
6949
|
+
id: createStorageErrorId("PG", "LIST_PROMPT_BLOCKS", "INVALID_PAGE"),
|
|
6950
|
+
domain: ErrorDomain.STORAGE,
|
|
6951
|
+
category: ErrorCategory.USER,
|
|
6952
|
+
details: { page }
|
|
6953
|
+
},
|
|
6954
|
+
new Error("page must be >= 0")
|
|
6955
|
+
);
|
|
6956
|
+
}
|
|
6957
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
6958
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
6959
|
+
try {
|
|
6960
|
+
const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
|
|
6961
|
+
const conditions = [];
|
|
6962
|
+
const queryParams = [];
|
|
6963
|
+
let paramIdx = 1;
|
|
6964
|
+
if (authorId !== void 0) {
|
|
6965
|
+
conditions.push(`"authorId" = $${paramIdx++}`);
|
|
6966
|
+
queryParams.push(authorId);
|
|
6967
|
+
}
|
|
6968
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
6969
|
+
conditions.push(`metadata @> $${paramIdx++}::jsonb`);
|
|
6970
|
+
queryParams.push(JSON.stringify(metadata));
|
|
6971
|
+
}
|
|
6972
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
6973
|
+
const countResult = await this.#db.client.one(
|
|
6974
|
+
`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
|
|
6975
|
+
queryParams
|
|
6976
|
+
);
|
|
6977
|
+
const total = parseInt(countResult.count, 10);
|
|
6978
|
+
if (total === 0) {
|
|
6979
|
+
return {
|
|
6980
|
+
promptBlocks: [],
|
|
6981
|
+
total: 0,
|
|
6982
|
+
page,
|
|
6983
|
+
perPage: perPageForResponse,
|
|
6984
|
+
hasMore: false
|
|
6985
|
+
};
|
|
6986
|
+
}
|
|
6987
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
6988
|
+
const dataResult = await this.#db.client.manyOrNone(
|
|
6989
|
+
`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
|
|
6990
|
+
[...queryParams, limitValue, offset]
|
|
6991
|
+
);
|
|
6992
|
+
const promptBlocks = (dataResult || []).map((row) => this.parseBlockRow(row));
|
|
6993
|
+
return {
|
|
6994
|
+
promptBlocks,
|
|
6995
|
+
total,
|
|
6996
|
+
page,
|
|
6997
|
+
perPage: perPageForResponse,
|
|
6998
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
6999
|
+
};
|
|
7000
|
+
} catch (error) {
|
|
7001
|
+
if (error instanceof MastraError) throw error;
|
|
7002
|
+
throw new MastraError(
|
|
7003
|
+
{
|
|
7004
|
+
id: createStorageErrorId("PG", "LIST_PROMPT_BLOCKS", "FAILED"),
|
|
7005
|
+
domain: ErrorDomain.STORAGE,
|
|
7006
|
+
category: ErrorCategory.THIRD_PARTY
|
|
7007
|
+
},
|
|
7008
|
+
error
|
|
7009
|
+
);
|
|
7010
|
+
}
|
|
7011
|
+
}
|
|
7012
|
+
// ==========================================================================
|
|
7013
|
+
// Prompt Block Version Methods
|
|
7014
|
+
// ==========================================================================
|
|
7015
|
+
async createVersion(input) {
|
|
7016
|
+
try {
|
|
7017
|
+
const tableName = getTableName2({
|
|
7018
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7019
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7020
|
+
});
|
|
7021
|
+
const now = /* @__PURE__ */ new Date();
|
|
7022
|
+
const nowIso = now.toISOString();
|
|
7023
|
+
await this.#db.client.none(
|
|
7024
|
+
`INSERT INTO ${tableName} (
|
|
7025
|
+
id, "blockId", "versionNumber",
|
|
7026
|
+
name, description, content, rules,
|
|
7027
|
+
"changedFields", "changeMessage",
|
|
7028
|
+
"createdAt", "createdAtZ"
|
|
7029
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
|
7030
|
+
[
|
|
7031
|
+
input.id,
|
|
7032
|
+
input.blockId,
|
|
7033
|
+
input.versionNumber,
|
|
7034
|
+
input.name,
|
|
7035
|
+
input.description ?? null,
|
|
7036
|
+
input.content,
|
|
7037
|
+
input.rules ? JSON.stringify(input.rules) : null,
|
|
7038
|
+
input.changedFields ? JSON.stringify(input.changedFields) : null,
|
|
7039
|
+
input.changeMessage ?? null,
|
|
7040
|
+
nowIso,
|
|
7041
|
+
nowIso
|
|
7042
|
+
]
|
|
7043
|
+
);
|
|
7044
|
+
return {
|
|
7045
|
+
...input,
|
|
7046
|
+
createdAt: now
|
|
7047
|
+
};
|
|
7048
|
+
} catch (error) {
|
|
7049
|
+
if (error instanceof MastraError) throw error;
|
|
7050
|
+
throw new MastraError(
|
|
7051
|
+
{
|
|
7052
|
+
id: createStorageErrorId("PG", "CREATE_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
7053
|
+
domain: ErrorDomain.STORAGE,
|
|
7054
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7055
|
+
details: { versionId: input.id, blockId: input.blockId }
|
|
7056
|
+
},
|
|
7057
|
+
error
|
|
7058
|
+
);
|
|
7059
|
+
}
|
|
7060
|
+
}
|
|
7061
|
+
async getVersion(id) {
|
|
7062
|
+
try {
|
|
7063
|
+
const tableName = getTableName2({
|
|
7064
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7065
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7066
|
+
});
|
|
7067
|
+
const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
|
|
7068
|
+
if (!result) {
|
|
7069
|
+
return null;
|
|
7070
|
+
}
|
|
7071
|
+
return this.parseVersionRow(result);
|
|
7072
|
+
} catch (error) {
|
|
7073
|
+
if (error instanceof MastraError) throw error;
|
|
7074
|
+
throw new MastraError(
|
|
7075
|
+
{
|
|
7076
|
+
id: createStorageErrorId("PG", "GET_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
7077
|
+
domain: ErrorDomain.STORAGE,
|
|
7078
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7079
|
+
details: { versionId: id }
|
|
7080
|
+
},
|
|
7081
|
+
error
|
|
7082
|
+
);
|
|
7083
|
+
}
|
|
7084
|
+
}
|
|
7085
|
+
async getVersionByNumber(blockId, versionNumber) {
|
|
7086
|
+
try {
|
|
7087
|
+
const tableName = getTableName2({
|
|
7088
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7089
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7090
|
+
});
|
|
7091
|
+
const result = await this.#db.client.oneOrNone(
|
|
7092
|
+
`SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`,
|
|
7093
|
+
[blockId, versionNumber]
|
|
7094
|
+
);
|
|
7095
|
+
if (!result) {
|
|
7096
|
+
return null;
|
|
7097
|
+
}
|
|
7098
|
+
return this.parseVersionRow(result);
|
|
7099
|
+
} catch (error) {
|
|
7100
|
+
if (error instanceof MastraError) throw error;
|
|
7101
|
+
throw new MastraError(
|
|
7102
|
+
{
|
|
7103
|
+
id: createStorageErrorId("PG", "GET_PROMPT_BLOCK_VERSION_BY_NUMBER", "FAILED"),
|
|
7104
|
+
domain: ErrorDomain.STORAGE,
|
|
7105
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7106
|
+
details: { blockId, versionNumber }
|
|
7107
|
+
},
|
|
7108
|
+
error
|
|
7109
|
+
);
|
|
7110
|
+
}
|
|
7111
|
+
}
|
|
7112
|
+
async getLatestVersion(blockId) {
|
|
7113
|
+
try {
|
|
7114
|
+
const tableName = getTableName2({
|
|
7115
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7116
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7117
|
+
});
|
|
7118
|
+
const result = await this.#db.client.oneOrNone(
|
|
7119
|
+
`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
|
|
7120
|
+
[blockId]
|
|
7121
|
+
);
|
|
7122
|
+
if (!result) {
|
|
7123
|
+
return null;
|
|
7124
|
+
}
|
|
7125
|
+
return this.parseVersionRow(result);
|
|
7126
|
+
} catch (error) {
|
|
7127
|
+
if (error instanceof MastraError) throw error;
|
|
7128
|
+
throw new MastraError(
|
|
7129
|
+
{
|
|
7130
|
+
id: createStorageErrorId("PG", "GET_LATEST_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
7131
|
+
domain: ErrorDomain.STORAGE,
|
|
7132
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7133
|
+
details: { blockId }
|
|
7134
|
+
},
|
|
7135
|
+
error
|
|
7136
|
+
);
|
|
7137
|
+
}
|
|
7138
|
+
}
|
|
7139
|
+
async listVersions(input) {
|
|
7140
|
+
const { blockId, page = 0, perPage: perPageInput, orderBy } = input;
|
|
7141
|
+
if (page < 0) {
|
|
7142
|
+
throw new MastraError(
|
|
7143
|
+
{
|
|
7144
|
+
id: createStorageErrorId("PG", "LIST_PROMPT_BLOCK_VERSIONS", "INVALID_PAGE"),
|
|
7145
|
+
domain: ErrorDomain.STORAGE,
|
|
7146
|
+
category: ErrorCategory.USER,
|
|
7147
|
+
details: { page }
|
|
7148
|
+
},
|
|
7149
|
+
new Error("page must be >= 0")
|
|
7150
|
+
);
|
|
7151
|
+
}
|
|
7152
|
+
const perPage = normalizePerPage(perPageInput, 20);
|
|
7153
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
7154
|
+
try {
|
|
7155
|
+
const { field, direction } = this.parseVersionOrderBy(orderBy);
|
|
7156
|
+
const tableName = getTableName2({
|
|
7157
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7158
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7159
|
+
});
|
|
7160
|
+
const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [
|
|
7161
|
+
blockId
|
|
7162
|
+
]);
|
|
7163
|
+
const total = parseInt(countResult.count, 10);
|
|
7164
|
+
if (total === 0) {
|
|
7165
|
+
return {
|
|
7166
|
+
versions: [],
|
|
7167
|
+
total: 0,
|
|
7168
|
+
page,
|
|
7169
|
+
perPage: perPageForResponse,
|
|
7170
|
+
hasMore: false
|
|
7171
|
+
};
|
|
7172
|
+
}
|
|
7173
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
7174
|
+
const dataResult = await this.#db.client.manyOrNone(
|
|
7175
|
+
`SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
|
|
7176
|
+
[blockId, limitValue, offset]
|
|
7177
|
+
);
|
|
7178
|
+
const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
|
|
7179
|
+
return {
|
|
7180
|
+
versions,
|
|
7181
|
+
total,
|
|
7182
|
+
page,
|
|
7183
|
+
perPage: perPageForResponse,
|
|
7184
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
7185
|
+
};
|
|
7186
|
+
} catch (error) {
|
|
7187
|
+
if (error instanceof MastraError) throw error;
|
|
7188
|
+
throw new MastraError(
|
|
7189
|
+
{
|
|
7190
|
+
id: createStorageErrorId("PG", "LIST_PROMPT_BLOCK_VERSIONS", "FAILED"),
|
|
7191
|
+
domain: ErrorDomain.STORAGE,
|
|
7192
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7193
|
+
details: { blockId }
|
|
7194
|
+
},
|
|
7195
|
+
error
|
|
7196
|
+
);
|
|
7197
|
+
}
|
|
7198
|
+
}
|
|
7199
|
+
async deleteVersion(id) {
|
|
7200
|
+
try {
|
|
7201
|
+
const tableName = getTableName2({
|
|
7202
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7203
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7204
|
+
});
|
|
7205
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
7206
|
+
} catch (error) {
|
|
7207
|
+
if (error instanceof MastraError) throw error;
|
|
7208
|
+
throw new MastraError(
|
|
7209
|
+
{
|
|
7210
|
+
id: createStorageErrorId("PG", "DELETE_PROMPT_BLOCK_VERSION", "FAILED"),
|
|
7211
|
+
domain: ErrorDomain.STORAGE,
|
|
7212
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7213
|
+
details: { versionId: id }
|
|
7214
|
+
},
|
|
7215
|
+
error
|
|
7216
|
+
);
|
|
7217
|
+
}
|
|
7218
|
+
}
|
|
7219
|
+
async deleteVersionsByParentId(entityId) {
|
|
7220
|
+
try {
|
|
7221
|
+
const tableName = getTableName2({
|
|
7222
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7223
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7224
|
+
});
|
|
7225
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE "blockId" = $1`, [entityId]);
|
|
7226
|
+
} catch (error) {
|
|
7227
|
+
if (error instanceof MastraError) throw error;
|
|
7228
|
+
throw new MastraError(
|
|
7229
|
+
{
|
|
7230
|
+
id: createStorageErrorId("PG", "DELETE_PROMPT_BLOCK_VERSIONS_BY_BLOCK_ID", "FAILED"),
|
|
7231
|
+
domain: ErrorDomain.STORAGE,
|
|
7232
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7233
|
+
details: { blockId: entityId }
|
|
7234
|
+
},
|
|
7235
|
+
error
|
|
7236
|
+
);
|
|
7237
|
+
}
|
|
7238
|
+
}
|
|
7239
|
+
async countVersions(blockId) {
|
|
7240
|
+
try {
|
|
7241
|
+
const tableName = getTableName2({
|
|
7242
|
+
indexName: TABLE_PROMPT_BLOCK_VERSIONS,
|
|
7243
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7244
|
+
});
|
|
7245
|
+
const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [
|
|
7246
|
+
blockId
|
|
7247
|
+
]);
|
|
7248
|
+
return parseInt(result.count, 10);
|
|
7249
|
+
} catch (error) {
|
|
7250
|
+
if (error instanceof MastraError) throw error;
|
|
7251
|
+
throw new MastraError(
|
|
7252
|
+
{
|
|
7253
|
+
id: createStorageErrorId("PG", "COUNT_PROMPT_BLOCK_VERSIONS", "FAILED"),
|
|
7254
|
+
domain: ErrorDomain.STORAGE,
|
|
7255
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7256
|
+
details: { blockId }
|
|
7257
|
+
},
|
|
7258
|
+
error
|
|
7259
|
+
);
|
|
7260
|
+
}
|
|
7261
|
+
}
|
|
7262
|
+
// ==========================================================================
|
|
7263
|
+
// Private Helper Methods
|
|
7264
|
+
// ==========================================================================
|
|
7265
|
+
parseJson(value, fieldName) {
|
|
7266
|
+
if (!value) return void 0;
|
|
7267
|
+
if (typeof value !== "string") return value;
|
|
7268
|
+
try {
|
|
7269
|
+
return JSON.parse(value);
|
|
7270
|
+
} catch (error) {
|
|
7271
|
+
const details = {
|
|
7272
|
+
value: value.length > 100 ? value.substring(0, 100) + "..." : value
|
|
7273
|
+
};
|
|
7274
|
+
if (fieldName) {
|
|
7275
|
+
details.field = fieldName;
|
|
7276
|
+
}
|
|
7277
|
+
throw new MastraError(
|
|
7278
|
+
{
|
|
7279
|
+
id: createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
|
|
7280
|
+
domain: ErrorDomain.STORAGE,
|
|
7281
|
+
category: ErrorCategory.SYSTEM,
|
|
7282
|
+
text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
7283
|
+
details
|
|
7284
|
+
},
|
|
7285
|
+
error
|
|
7286
|
+
);
|
|
7287
|
+
}
|
|
7288
|
+
}
|
|
7289
|
+
parseBlockRow(row) {
|
|
7290
|
+
return {
|
|
7291
|
+
id: row.id,
|
|
7292
|
+
status: row.status,
|
|
7293
|
+
activeVersionId: row.activeVersionId,
|
|
7294
|
+
authorId: row.authorId,
|
|
7295
|
+
metadata: this.parseJson(row.metadata, "metadata"),
|
|
7296
|
+
createdAt: new Date(row.createdAtZ || row.createdAt),
|
|
7297
|
+
updatedAt: new Date(row.updatedAtZ || row.updatedAt)
|
|
7298
|
+
};
|
|
7299
|
+
}
|
|
7300
|
+
parseVersionRow(row) {
|
|
7301
|
+
return {
|
|
7302
|
+
id: row.id,
|
|
7303
|
+
blockId: row.blockId,
|
|
7304
|
+
versionNumber: row.versionNumber,
|
|
7305
|
+
name: row.name,
|
|
7306
|
+
description: row.description,
|
|
7307
|
+
content: row.content,
|
|
7308
|
+
rules: this.parseJson(row.rules, "rules"),
|
|
7309
|
+
changedFields: this.parseJson(row.changedFields, "changedFields"),
|
|
7310
|
+
changeMessage: row.changeMessage,
|
|
7311
|
+
createdAt: new Date(row.createdAtZ || row.createdAt)
|
|
7312
|
+
};
|
|
7313
|
+
}
|
|
7314
|
+
};
|
|
7315
|
+
var SNAPSHOT_FIELDS2 = [
|
|
7316
|
+
"name",
|
|
7317
|
+
"description",
|
|
7318
|
+
"type",
|
|
7319
|
+
"model",
|
|
7320
|
+
"instructions",
|
|
7321
|
+
"scoreRange",
|
|
7322
|
+
"presetConfig",
|
|
7323
|
+
"defaultSampling"
|
|
7324
|
+
];
|
|
7325
|
+
var ScorerDefinitionsPG = class _ScorerDefinitionsPG extends ScorerDefinitionsStorage {
|
|
7326
|
+
#db;
|
|
7327
|
+
#schema;
|
|
7328
|
+
#skipDefaultIndexes;
|
|
7329
|
+
#indexes;
|
|
7330
|
+
static MANAGED_TABLES = [TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS];
|
|
7331
|
+
constructor(config) {
|
|
7332
|
+
super();
|
|
7333
|
+
const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
|
|
7334
|
+
this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
|
|
7335
|
+
this.#schema = schemaName || "public";
|
|
7336
|
+
this.#skipDefaultIndexes = skipDefaultIndexes;
|
|
7337
|
+
this.#indexes = indexes?.filter(
|
|
7338
|
+
(idx) => _ScorerDefinitionsPG.MANAGED_TABLES.includes(idx.table)
|
|
7339
|
+
);
|
|
7340
|
+
}
|
|
7341
|
+
getDefaultIndexDefinitions() {
|
|
7342
|
+
return [
|
|
7343
|
+
{
|
|
7344
|
+
name: "idx_scorer_definition_versions_def_version",
|
|
7345
|
+
table: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7346
|
+
columns: ["scorerDefinitionId", "versionNumber"],
|
|
7347
|
+
unique: true
|
|
7348
|
+
}
|
|
7349
|
+
];
|
|
7350
|
+
}
|
|
7351
|
+
async createDefaultIndexes() {
|
|
7352
|
+
if (this.#skipDefaultIndexes) {
|
|
7353
|
+
return;
|
|
7354
|
+
}
|
|
7355
|
+
for (const indexDef of this.getDefaultIndexDefinitions()) {
|
|
7356
|
+
try {
|
|
7357
|
+
await this.#db.createIndex(indexDef);
|
|
7358
|
+
} catch {
|
|
7359
|
+
}
|
|
7360
|
+
}
|
|
7361
|
+
}
|
|
7362
|
+
async init() {
|
|
7363
|
+
await this.#db.createTable({
|
|
7364
|
+
tableName: TABLE_SCORER_DEFINITIONS,
|
|
7365
|
+
schema: TABLE_SCHEMAS[TABLE_SCORER_DEFINITIONS]
|
|
7366
|
+
});
|
|
7367
|
+
await this.#db.createTable({
|
|
7368
|
+
tableName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7369
|
+
schema: TABLE_SCHEMAS[TABLE_SCORER_DEFINITION_VERSIONS]
|
|
7370
|
+
});
|
|
7371
|
+
await this.createDefaultIndexes();
|
|
7372
|
+
await this.createCustomIndexes();
|
|
7373
|
+
}
|
|
7374
|
+
async createCustomIndexes() {
|
|
7375
|
+
if (!this.#indexes || this.#indexes.length === 0) {
|
|
7376
|
+
return;
|
|
7377
|
+
}
|
|
7378
|
+
for (const indexDef of this.#indexes) {
|
|
7379
|
+
try {
|
|
7380
|
+
await this.#db.createIndex(indexDef);
|
|
7381
|
+
} catch (error) {
|
|
7382
|
+
this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
|
|
7383
|
+
}
|
|
7384
|
+
}
|
|
7385
|
+
}
|
|
7386
|
+
async dangerouslyClearAll() {
|
|
7387
|
+
await this.#db.clearTable({ tableName: TABLE_SCORER_DEFINITION_VERSIONS });
|
|
7388
|
+
await this.#db.clearTable({ tableName: TABLE_SCORER_DEFINITIONS });
|
|
7389
|
+
}
|
|
7390
|
+
// ==========================================================================
|
|
7391
|
+
// Scorer Definition CRUD Methods
|
|
7392
|
+
// ==========================================================================
|
|
7393
|
+
async getById(id) {
|
|
7394
|
+
try {
|
|
7395
|
+
const tableName = getTableName2({ indexName: TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
|
|
7396
|
+
const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
|
|
7397
|
+
if (!result) {
|
|
7398
|
+
return null;
|
|
7399
|
+
}
|
|
7400
|
+
return this.parseScorerRow(result);
|
|
7401
|
+
} catch (error) {
|
|
7402
|
+
if (error instanceof MastraError) throw error;
|
|
7403
|
+
throw new MastraError(
|
|
7404
|
+
{
|
|
7405
|
+
id: createStorageErrorId("PG", "GET_SCORER_DEFINITION_BY_ID", "FAILED"),
|
|
7406
|
+
domain: ErrorDomain.STORAGE,
|
|
7407
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7408
|
+
details: { scorerDefinitionId: id }
|
|
7409
|
+
},
|
|
7410
|
+
error
|
|
7411
|
+
);
|
|
7412
|
+
}
|
|
7413
|
+
}
|
|
7414
|
+
async create(input) {
|
|
7415
|
+
const { scorerDefinition } = input;
|
|
7416
|
+
try {
|
|
7417
|
+
const tableName = getTableName2({ indexName: TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
|
|
7418
|
+
const now = /* @__PURE__ */ new Date();
|
|
7419
|
+
const nowIso = now.toISOString();
|
|
7420
|
+
await this.#db.client.none(
|
|
7421
|
+
`INSERT INTO ${tableName} (
|
|
7422
|
+
id, status, "activeVersionId", "authorId", metadata,
|
|
7423
|
+
"createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
7424
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
|
7425
|
+
[
|
|
7426
|
+
scorerDefinition.id,
|
|
7427
|
+
"draft",
|
|
7428
|
+
null,
|
|
7429
|
+
scorerDefinition.authorId ?? null,
|
|
7430
|
+
scorerDefinition.metadata ? JSON.stringify(scorerDefinition.metadata) : null,
|
|
7431
|
+
nowIso,
|
|
7432
|
+
nowIso,
|
|
7433
|
+
nowIso,
|
|
7434
|
+
nowIso
|
|
7435
|
+
]
|
|
7436
|
+
);
|
|
7437
|
+
const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
|
|
7438
|
+
const versionId = crypto.randomUUID();
|
|
7439
|
+
await this.createVersion({
|
|
7440
|
+
id: versionId,
|
|
7441
|
+
scorerDefinitionId: scorerDefinition.id,
|
|
7442
|
+
versionNumber: 1,
|
|
7443
|
+
...snapshotConfig,
|
|
7444
|
+
changedFields: [...SNAPSHOT_FIELDS2],
|
|
7445
|
+
changeMessage: "Initial version"
|
|
7446
|
+
});
|
|
7447
|
+
return {
|
|
7448
|
+
id: scorerDefinition.id,
|
|
7449
|
+
status: "draft",
|
|
7450
|
+
activeVersionId: void 0,
|
|
7451
|
+
authorId: scorerDefinition.authorId,
|
|
7452
|
+
metadata: scorerDefinition.metadata,
|
|
7453
|
+
createdAt: now,
|
|
7454
|
+
updatedAt: now
|
|
7455
|
+
};
|
|
7456
|
+
} catch (error) {
|
|
7457
|
+
try {
|
|
7458
|
+
const tableName = getTableName2({
|
|
7459
|
+
indexName: TABLE_SCORER_DEFINITIONS,
|
|
7460
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7461
|
+
});
|
|
7462
|
+
await this.#db.client.none(
|
|
7463
|
+
`DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
|
|
7464
|
+
[scorerDefinition.id]
|
|
7465
|
+
);
|
|
7466
|
+
} catch {
|
|
7467
|
+
}
|
|
7468
|
+
if (error instanceof MastraError) throw error;
|
|
7469
|
+
throw new MastraError(
|
|
7470
|
+
{
|
|
7471
|
+
id: createStorageErrorId("PG", "CREATE_SCORER_DEFINITION", "FAILED"),
|
|
7472
|
+
domain: ErrorDomain.STORAGE,
|
|
7473
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7474
|
+
details: { scorerDefinitionId: scorerDefinition.id }
|
|
7475
|
+
},
|
|
7476
|
+
error
|
|
7477
|
+
);
|
|
7478
|
+
}
|
|
7479
|
+
}
|
|
7480
|
+
async update(input) {
|
|
7481
|
+
const { id, ...updates } = input;
|
|
7482
|
+
try {
|
|
7483
|
+
const tableName = getTableName2({ indexName: TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
|
|
7484
|
+
const existingScorer = await this.getById(id);
|
|
7485
|
+
if (!existingScorer) {
|
|
7486
|
+
throw new MastraError({
|
|
7487
|
+
id: createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
|
|
7488
|
+
domain: ErrorDomain.STORAGE,
|
|
7489
|
+
category: ErrorCategory.USER,
|
|
7490
|
+
text: `Scorer definition ${id} not found`,
|
|
7491
|
+
details: { scorerDefinitionId: id }
|
|
7492
|
+
});
|
|
7493
|
+
}
|
|
7494
|
+
const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
|
|
7495
|
+
let versionCreated = false;
|
|
7496
|
+
const hasConfigUpdate = SNAPSHOT_FIELDS2.some((field) => field in configFields);
|
|
7497
|
+
if (hasConfigUpdate) {
|
|
7498
|
+
const latestVersion = await this.getLatestVersion(id);
|
|
7499
|
+
if (!latestVersion) {
|
|
7500
|
+
throw new MastraError({
|
|
7501
|
+
id: createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NO_VERSIONS"),
|
|
7502
|
+
domain: ErrorDomain.STORAGE,
|
|
7503
|
+
category: ErrorCategory.SYSTEM,
|
|
7504
|
+
text: `No versions found for scorer definition ${id}`,
|
|
7505
|
+
details: { scorerDefinitionId: id }
|
|
7506
|
+
});
|
|
7507
|
+
}
|
|
7508
|
+
const {
|
|
7509
|
+
id: _versionId,
|
|
7510
|
+
scorerDefinitionId: _scorerDefinitionId,
|
|
7511
|
+
versionNumber: _versionNumber,
|
|
7512
|
+
changedFields: _changedFields,
|
|
7513
|
+
changeMessage: _changeMessage,
|
|
7514
|
+
createdAt: _createdAt,
|
|
7515
|
+
...latestConfig
|
|
7516
|
+
} = latestVersion;
|
|
7517
|
+
const newConfig = { ...latestConfig, ...configFields };
|
|
7518
|
+
const changedFields = SNAPSHOT_FIELDS2.filter(
|
|
7519
|
+
(field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
|
|
7520
|
+
);
|
|
7521
|
+
if (changedFields.length > 0) {
|
|
7522
|
+
versionCreated = true;
|
|
7523
|
+
const newVersionId = crypto.randomUUID();
|
|
7524
|
+
await this.createVersion({
|
|
7525
|
+
id: newVersionId,
|
|
7526
|
+
scorerDefinitionId: id,
|
|
7527
|
+
versionNumber: latestVersion.versionNumber + 1,
|
|
7528
|
+
...newConfig,
|
|
7529
|
+
changedFields: [...changedFields],
|
|
7530
|
+
changeMessage: `Updated ${changedFields.join(", ")}`
|
|
7531
|
+
});
|
|
7532
|
+
}
|
|
7533
|
+
}
|
|
7534
|
+
const setClauses = [];
|
|
7535
|
+
const values = [];
|
|
7536
|
+
let paramIndex = 1;
|
|
7537
|
+
if (authorId !== void 0) {
|
|
7538
|
+
setClauses.push(`"authorId" = $${paramIndex++}`);
|
|
7539
|
+
values.push(authorId);
|
|
7540
|
+
}
|
|
7541
|
+
if (activeVersionId !== void 0) {
|
|
7542
|
+
setClauses.push(`"activeVersionId" = $${paramIndex++}`);
|
|
7543
|
+
values.push(activeVersionId);
|
|
7544
|
+
if (status === void 0) {
|
|
7545
|
+
setClauses.push(`status = $${paramIndex++}`);
|
|
7546
|
+
values.push("published");
|
|
7547
|
+
}
|
|
7548
|
+
}
|
|
7549
|
+
if (status !== void 0) {
|
|
7550
|
+
setClauses.push(`status = $${paramIndex++}`);
|
|
7551
|
+
values.push(status);
|
|
7552
|
+
}
|
|
7553
|
+
if (metadata !== void 0) {
|
|
7554
|
+
const mergedMetadata = { ...existingScorer.metadata || {}, ...metadata };
|
|
7555
|
+
setClauses.push(`metadata = $${paramIndex++}`);
|
|
7556
|
+
values.push(JSON.stringify(mergedMetadata));
|
|
7557
|
+
}
|
|
7558
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
7559
|
+
setClauses.push(`"updatedAt" = $${paramIndex++}`);
|
|
7560
|
+
values.push(now);
|
|
7561
|
+
setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
|
|
7562
|
+
values.push(now);
|
|
7563
|
+
values.push(id);
|
|
7564
|
+
if (setClauses.length > 2 || versionCreated) {
|
|
7565
|
+
await this.#db.client.none(
|
|
7566
|
+
`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`,
|
|
7567
|
+
values
|
|
7568
|
+
);
|
|
7569
|
+
}
|
|
7570
|
+
const updatedScorer = await this.getById(id);
|
|
7571
|
+
if (!updatedScorer) {
|
|
7572
|
+
throw new MastraError({
|
|
7573
|
+
id: createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
|
|
7574
|
+
domain: ErrorDomain.STORAGE,
|
|
7575
|
+
category: ErrorCategory.SYSTEM,
|
|
7576
|
+
text: `Scorer definition ${id} not found after update`,
|
|
7577
|
+
details: { scorerDefinitionId: id }
|
|
7578
|
+
});
|
|
7579
|
+
}
|
|
7580
|
+
return updatedScorer;
|
|
7581
|
+
} catch (error) {
|
|
7582
|
+
if (error instanceof MastraError) throw error;
|
|
7583
|
+
throw new MastraError(
|
|
7584
|
+
{
|
|
7585
|
+
id: createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "FAILED"),
|
|
7586
|
+
domain: ErrorDomain.STORAGE,
|
|
7587
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7588
|
+
details: { scorerDefinitionId: id }
|
|
7589
|
+
},
|
|
7590
|
+
error
|
|
7591
|
+
);
|
|
7592
|
+
}
|
|
7593
|
+
}
|
|
7594
|
+
async delete(id) {
|
|
7595
|
+
try {
|
|
7596
|
+
const tableName = getTableName2({ indexName: TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
|
|
7597
|
+
await this.deleteVersionsByParentId(id);
|
|
7598
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
7599
|
+
} catch (error) {
|
|
7600
|
+
if (error instanceof MastraError) throw error;
|
|
7601
|
+
throw new MastraError(
|
|
7602
|
+
{
|
|
7603
|
+
id: createStorageErrorId("PG", "DELETE_SCORER_DEFINITION", "FAILED"),
|
|
7604
|
+
domain: ErrorDomain.STORAGE,
|
|
7605
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7606
|
+
details: { scorerDefinitionId: id }
|
|
7607
|
+
},
|
|
7608
|
+
error
|
|
7609
|
+
);
|
|
7610
|
+
}
|
|
7611
|
+
}
|
|
7612
|
+
async list(args) {
|
|
7613
|
+
const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
|
|
7614
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
7615
|
+
if (page < 0) {
|
|
7616
|
+
throw new MastraError(
|
|
7617
|
+
{
|
|
7618
|
+
id: createStorageErrorId("PG", "LIST_SCORER_DEFINITIONS", "INVALID_PAGE"),
|
|
7619
|
+
domain: ErrorDomain.STORAGE,
|
|
7620
|
+
category: ErrorCategory.USER,
|
|
7621
|
+
details: { page }
|
|
7622
|
+
},
|
|
7623
|
+
new Error("page must be >= 0")
|
|
7624
|
+
);
|
|
7625
|
+
}
|
|
7626
|
+
const perPage = normalizePerPage(perPageInput, 100);
|
|
7627
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
7628
|
+
try {
|
|
7629
|
+
const tableName = getTableName2({ indexName: TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
|
|
7630
|
+
const conditions = [];
|
|
7631
|
+
const queryParams = [];
|
|
7632
|
+
let paramIdx = 1;
|
|
7633
|
+
if (authorId !== void 0) {
|
|
7634
|
+
conditions.push(`"authorId" = $${paramIdx++}`);
|
|
7635
|
+
queryParams.push(authorId);
|
|
7636
|
+
}
|
|
7637
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
7638
|
+
conditions.push(`metadata @> $${paramIdx++}::jsonb`);
|
|
7639
|
+
queryParams.push(JSON.stringify(metadata));
|
|
7640
|
+
}
|
|
7641
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
7642
|
+
const countResult = await this.#db.client.one(
|
|
7643
|
+
`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
|
|
7644
|
+
queryParams
|
|
7645
|
+
);
|
|
7646
|
+
const total = parseInt(countResult.count, 10);
|
|
7647
|
+
if (total === 0) {
|
|
7648
|
+
return {
|
|
7649
|
+
scorerDefinitions: [],
|
|
7650
|
+
total: 0,
|
|
7651
|
+
page,
|
|
7652
|
+
perPage: perPageForResponse,
|
|
7653
|
+
hasMore: false
|
|
7654
|
+
};
|
|
7655
|
+
}
|
|
7656
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
7657
|
+
const dataResult = await this.#db.client.manyOrNone(
|
|
7658
|
+
`SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
|
|
7659
|
+
[...queryParams, limitValue, offset]
|
|
7660
|
+
);
|
|
7661
|
+
const scorerDefinitions = (dataResult || []).map((row) => this.parseScorerRow(row));
|
|
7662
|
+
return {
|
|
7663
|
+
scorerDefinitions,
|
|
7664
|
+
total,
|
|
7665
|
+
page,
|
|
7666
|
+
perPage: perPageForResponse,
|
|
7667
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
7668
|
+
};
|
|
7669
|
+
} catch (error) {
|
|
7670
|
+
if (error instanceof MastraError) throw error;
|
|
7671
|
+
throw new MastraError(
|
|
7672
|
+
{
|
|
7673
|
+
id: createStorageErrorId("PG", "LIST_SCORER_DEFINITIONS", "FAILED"),
|
|
7674
|
+
domain: ErrorDomain.STORAGE,
|
|
7675
|
+
category: ErrorCategory.THIRD_PARTY
|
|
7676
|
+
},
|
|
7677
|
+
error
|
|
7678
|
+
);
|
|
7679
|
+
}
|
|
7680
|
+
}
|
|
7681
|
+
// ==========================================================================
|
|
7682
|
+
// Scorer Definition Version Methods
|
|
7683
|
+
// ==========================================================================
|
|
7684
|
+
async createVersion(input) {
|
|
7685
|
+
try {
|
|
7686
|
+
const tableName = getTableName2({
|
|
7687
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7688
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7689
|
+
});
|
|
7690
|
+
const now = /* @__PURE__ */ new Date();
|
|
7691
|
+
const nowIso = now.toISOString();
|
|
7692
|
+
await this.#db.client.none(
|
|
7693
|
+
`INSERT INTO ${tableName} (
|
|
7694
|
+
id, "scorerDefinitionId", "versionNumber",
|
|
7695
|
+
name, description, type, model, instructions, "scoreRange", "presetConfig", "defaultSampling",
|
|
7696
|
+
"changedFields", "changeMessage",
|
|
7697
|
+
"createdAt", "createdAtZ"
|
|
7698
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,
|
|
7699
|
+
[
|
|
7700
|
+
input.id,
|
|
7701
|
+
input.scorerDefinitionId,
|
|
7702
|
+
input.versionNumber,
|
|
7703
|
+
input.name,
|
|
7704
|
+
input.description ?? null,
|
|
7705
|
+
input.type,
|
|
7706
|
+
input.model ? JSON.stringify(input.model) : null,
|
|
7707
|
+
input.instructions ?? null,
|
|
7708
|
+
input.scoreRange ? JSON.stringify(input.scoreRange) : null,
|
|
7709
|
+
input.presetConfig ? JSON.stringify(input.presetConfig) : null,
|
|
7710
|
+
input.defaultSampling ? JSON.stringify(input.defaultSampling) : null,
|
|
7711
|
+
input.changedFields ? JSON.stringify(input.changedFields) : null,
|
|
7712
|
+
input.changeMessage ?? null,
|
|
7713
|
+
nowIso,
|
|
7714
|
+
nowIso
|
|
7715
|
+
]
|
|
7716
|
+
);
|
|
7717
|
+
return {
|
|
7718
|
+
...input,
|
|
7719
|
+
createdAt: now
|
|
7720
|
+
};
|
|
7721
|
+
} catch (error) {
|
|
7722
|
+
if (error instanceof MastraError) throw error;
|
|
7723
|
+
throw new MastraError(
|
|
7724
|
+
{
|
|
7725
|
+
id: createStorageErrorId("PG", "CREATE_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
7726
|
+
domain: ErrorDomain.STORAGE,
|
|
7727
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7728
|
+
details: { versionId: input.id, scorerDefinitionId: input.scorerDefinitionId }
|
|
7729
|
+
},
|
|
7730
|
+
error
|
|
7731
|
+
);
|
|
7732
|
+
}
|
|
7733
|
+
}
|
|
7734
|
+
async getVersion(id) {
|
|
7735
|
+
try {
|
|
7736
|
+
const tableName = getTableName2({
|
|
7737
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7738
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7739
|
+
});
|
|
7740
|
+
const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
|
|
7741
|
+
if (!result) {
|
|
7742
|
+
return null;
|
|
7743
|
+
}
|
|
7744
|
+
return this.parseVersionRow(result);
|
|
7745
|
+
} catch (error) {
|
|
7746
|
+
if (error instanceof MastraError) throw error;
|
|
7747
|
+
throw new MastraError(
|
|
7748
|
+
{
|
|
7749
|
+
id: createStorageErrorId("PG", "GET_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
7750
|
+
domain: ErrorDomain.STORAGE,
|
|
7751
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7752
|
+
details: { versionId: id }
|
|
7753
|
+
},
|
|
7754
|
+
error
|
|
7755
|
+
);
|
|
7756
|
+
}
|
|
7757
|
+
}
|
|
7758
|
+
async getVersionByNumber(scorerDefinitionId, versionNumber) {
|
|
7759
|
+
try {
|
|
7760
|
+
const tableName = getTableName2({
|
|
7761
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7762
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7763
|
+
});
|
|
7764
|
+
const result = await this.#db.client.oneOrNone(
|
|
7765
|
+
`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`,
|
|
7766
|
+
[scorerDefinitionId, versionNumber]
|
|
7767
|
+
);
|
|
7768
|
+
if (!result) {
|
|
7769
|
+
return null;
|
|
7770
|
+
}
|
|
7771
|
+
return this.parseVersionRow(result);
|
|
7772
|
+
} catch (error) {
|
|
7773
|
+
if (error instanceof MastraError) throw error;
|
|
7774
|
+
throw new MastraError(
|
|
7775
|
+
{
|
|
7776
|
+
id: createStorageErrorId("PG", "GET_SCORER_DEFINITION_VERSION_BY_NUMBER", "FAILED"),
|
|
7777
|
+
domain: ErrorDomain.STORAGE,
|
|
7778
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7779
|
+
details: { scorerDefinitionId, versionNumber }
|
|
7780
|
+
},
|
|
7781
|
+
error
|
|
7782
|
+
);
|
|
7783
|
+
}
|
|
7784
|
+
}
|
|
7785
|
+
async getLatestVersion(scorerDefinitionId) {
|
|
7786
|
+
try {
|
|
7787
|
+
const tableName = getTableName2({
|
|
7788
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7789
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7790
|
+
});
|
|
7791
|
+
const result = await this.#db.client.oneOrNone(
|
|
7792
|
+
`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
|
|
7793
|
+
[scorerDefinitionId]
|
|
7794
|
+
);
|
|
7795
|
+
if (!result) {
|
|
7796
|
+
return null;
|
|
7797
|
+
}
|
|
7798
|
+
return this.parseVersionRow(result);
|
|
7799
|
+
} catch (error) {
|
|
7800
|
+
if (error instanceof MastraError) throw error;
|
|
7801
|
+
throw new MastraError(
|
|
7802
|
+
{
|
|
7803
|
+
id: createStorageErrorId("PG", "GET_LATEST_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
7804
|
+
domain: ErrorDomain.STORAGE,
|
|
7805
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7806
|
+
details: { scorerDefinitionId }
|
|
7807
|
+
},
|
|
7808
|
+
error
|
|
7809
|
+
);
|
|
7810
|
+
}
|
|
7811
|
+
}
|
|
7812
|
+
async listVersions(input) {
|
|
7813
|
+
const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
|
|
7814
|
+
if (page < 0) {
|
|
7815
|
+
throw new MastraError(
|
|
7816
|
+
{
|
|
7817
|
+
id: createStorageErrorId("PG", "LIST_SCORER_DEFINITION_VERSIONS", "INVALID_PAGE"),
|
|
7818
|
+
domain: ErrorDomain.STORAGE,
|
|
7819
|
+
category: ErrorCategory.USER,
|
|
7820
|
+
details: { page }
|
|
7821
|
+
},
|
|
7822
|
+
new Error("page must be >= 0")
|
|
7823
|
+
);
|
|
7824
|
+
}
|
|
7825
|
+
const perPage = normalizePerPage(perPageInput, 20);
|
|
7826
|
+
const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
|
|
7827
|
+
try {
|
|
7828
|
+
const { field, direction } = this.parseVersionOrderBy(orderBy);
|
|
7829
|
+
const tableName = getTableName2({
|
|
7830
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7831
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7832
|
+
});
|
|
7833
|
+
const countResult = await this.#db.client.one(
|
|
7834
|
+
`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`,
|
|
7835
|
+
[scorerDefinitionId]
|
|
7836
|
+
);
|
|
7837
|
+
const total = parseInt(countResult.count, 10);
|
|
7838
|
+
if (total === 0) {
|
|
7839
|
+
return {
|
|
7840
|
+
versions: [],
|
|
7841
|
+
total: 0,
|
|
7842
|
+
page,
|
|
7843
|
+
perPage: perPageForResponse,
|
|
7844
|
+
hasMore: false
|
|
7845
|
+
};
|
|
7846
|
+
}
|
|
7847
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
7848
|
+
const dataResult = await this.#db.client.manyOrNone(
|
|
7849
|
+
`SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
|
|
7850
|
+
[scorerDefinitionId, limitValue, offset]
|
|
7851
|
+
);
|
|
7852
|
+
const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
|
|
7853
|
+
return {
|
|
7854
|
+
versions,
|
|
7855
|
+
total,
|
|
7856
|
+
page,
|
|
7857
|
+
perPage: perPageForResponse,
|
|
7858
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
7859
|
+
};
|
|
7860
|
+
} catch (error) {
|
|
7861
|
+
if (error instanceof MastraError) throw error;
|
|
7862
|
+
throw new MastraError(
|
|
7863
|
+
{
|
|
7864
|
+
id: createStorageErrorId("PG", "LIST_SCORER_DEFINITION_VERSIONS", "FAILED"),
|
|
7865
|
+
domain: ErrorDomain.STORAGE,
|
|
7866
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7867
|
+
details: { scorerDefinitionId }
|
|
7868
|
+
},
|
|
7869
|
+
error
|
|
7870
|
+
);
|
|
7871
|
+
}
|
|
7872
|
+
}
|
|
7873
|
+
async deleteVersion(id) {
|
|
7874
|
+
try {
|
|
7875
|
+
const tableName = getTableName2({
|
|
7876
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7877
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7878
|
+
});
|
|
7879
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
|
|
7880
|
+
} catch (error) {
|
|
7881
|
+
if (error instanceof MastraError) throw error;
|
|
7882
|
+
throw new MastraError(
|
|
7883
|
+
{
|
|
7884
|
+
id: createStorageErrorId("PG", "DELETE_SCORER_DEFINITION_VERSION", "FAILED"),
|
|
7885
|
+
domain: ErrorDomain.STORAGE,
|
|
7886
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7887
|
+
details: { versionId: id }
|
|
7888
|
+
},
|
|
7889
|
+
error
|
|
7890
|
+
);
|
|
7891
|
+
}
|
|
7892
|
+
}
|
|
7893
|
+
async deleteVersionsByParentId(entityId) {
|
|
7894
|
+
try {
|
|
7895
|
+
const tableName = getTableName2({
|
|
7896
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7897
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7898
|
+
});
|
|
7899
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [entityId]);
|
|
7900
|
+
} catch (error) {
|
|
7901
|
+
if (error instanceof MastraError) throw error;
|
|
7902
|
+
throw new MastraError(
|
|
7903
|
+
{
|
|
7904
|
+
id: createStorageErrorId("PG", "DELETE_SCORER_DEFINITION_VERSIONS_BY_SCORER_DEFINITION_ID", "FAILED"),
|
|
7905
|
+
domain: ErrorDomain.STORAGE,
|
|
7906
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7907
|
+
details: { scorerDefinitionId: entityId }
|
|
7908
|
+
},
|
|
7909
|
+
error
|
|
7910
|
+
);
|
|
7911
|
+
}
|
|
7912
|
+
}
|
|
7913
|
+
async countVersions(scorerDefinitionId) {
|
|
7914
|
+
try {
|
|
7915
|
+
const tableName = getTableName2({
|
|
7916
|
+
indexName: TABLE_SCORER_DEFINITION_VERSIONS,
|
|
7917
|
+
schemaName: getSchemaName2(this.#schema)
|
|
7918
|
+
});
|
|
7919
|
+
const result = await this.#db.client.one(
|
|
7920
|
+
`SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`,
|
|
7921
|
+
[scorerDefinitionId]
|
|
7922
|
+
);
|
|
7923
|
+
return parseInt(result.count, 10);
|
|
7924
|
+
} catch (error) {
|
|
7925
|
+
if (error instanceof MastraError) throw error;
|
|
7926
|
+
throw new MastraError(
|
|
7927
|
+
{
|
|
7928
|
+
id: createStorageErrorId("PG", "COUNT_SCORER_DEFINITION_VERSIONS", "FAILED"),
|
|
7929
|
+
domain: ErrorDomain.STORAGE,
|
|
7930
|
+
category: ErrorCategory.THIRD_PARTY,
|
|
7931
|
+
details: { scorerDefinitionId }
|
|
7932
|
+
},
|
|
7933
|
+
error
|
|
7934
|
+
);
|
|
7935
|
+
}
|
|
7936
|
+
}
|
|
7937
|
+
// ==========================================================================
|
|
7938
|
+
// Private Helper Methods
|
|
7939
|
+
// ==========================================================================
|
|
7940
|
+
parseJson(value, fieldName) {
|
|
7941
|
+
if (!value) return void 0;
|
|
7942
|
+
if (typeof value !== "string") return value;
|
|
7943
|
+
try {
|
|
7944
|
+
return JSON.parse(value);
|
|
7945
|
+
} catch (error) {
|
|
7946
|
+
if (error instanceof MastraError) throw error;
|
|
7947
|
+
const details = {
|
|
7948
|
+
value: value.length > 100 ? value.substring(0, 100) + "..." : value
|
|
7949
|
+
};
|
|
7950
|
+
if (fieldName) {
|
|
7951
|
+
details.field = fieldName;
|
|
7952
|
+
}
|
|
7953
|
+
throw new MastraError(
|
|
7954
|
+
{
|
|
7955
|
+
id: createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
|
|
7956
|
+
domain: ErrorDomain.STORAGE,
|
|
7957
|
+
category: ErrorCategory.SYSTEM,
|
|
7958
|
+
text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
7959
|
+
details
|
|
7960
|
+
},
|
|
7961
|
+
error
|
|
7962
|
+
);
|
|
7963
|
+
}
|
|
7964
|
+
}
|
|
7965
|
+
parseScorerRow(row) {
|
|
7966
|
+
return {
|
|
7967
|
+
id: row.id,
|
|
7968
|
+
status: row.status,
|
|
7969
|
+
activeVersionId: row.activeVersionId,
|
|
7970
|
+
authorId: row.authorId,
|
|
7971
|
+
metadata: this.parseJson(row.metadata, "metadata"),
|
|
7972
|
+
createdAt: new Date(row.createdAtZ || row.createdAt),
|
|
7973
|
+
updatedAt: new Date(row.updatedAtZ || row.updatedAt)
|
|
7974
|
+
};
|
|
7975
|
+
}
|
|
7976
|
+
parseVersionRow(row) {
|
|
7977
|
+
return {
|
|
7978
|
+
id: row.id,
|
|
7979
|
+
scorerDefinitionId: row.scorerDefinitionId,
|
|
7980
|
+
versionNumber: row.versionNumber,
|
|
7981
|
+
name: row.name,
|
|
7982
|
+
description: row.description,
|
|
7983
|
+
type: row.type,
|
|
7984
|
+
model: this.parseJson(row.model, "model"),
|
|
7985
|
+
instructions: row.instructions,
|
|
7986
|
+
scoreRange: this.parseJson(row.scoreRange, "scoreRange"),
|
|
7987
|
+
presetConfig: this.parseJson(row.presetConfig, "presetConfig"),
|
|
7988
|
+
defaultSampling: this.parseJson(row.defaultSampling, "defaultSampling"),
|
|
7989
|
+
changedFields: this.parseJson(row.changedFields, "changedFields"),
|
|
7990
|
+
changeMessage: row.changeMessage,
|
|
7991
|
+
createdAt: new Date(row.createdAtZ || row.createdAt)
|
|
7992
|
+
};
|
|
7993
|
+
}
|
|
7994
|
+
};
|
|
6218
7995
|
function getSchemaName4(schema) {
|
|
6219
7996
|
return schema ? `"${schema}"` : '"public"';
|
|
6220
7997
|
}
|
|
@@ -6936,7 +8713,9 @@ var PostgresStore = class extends MastraCompositeStore {
|
|
|
6936
8713
|
workflows: new WorkflowsPG(domainConfig),
|
|
6937
8714
|
memory: new MemoryPG(domainConfig),
|
|
6938
8715
|
observability: new ObservabilityPG(domainConfig),
|
|
6939
|
-
agents: new AgentsPG(domainConfig)
|
|
8716
|
+
agents: new AgentsPG(domainConfig),
|
|
8717
|
+
promptBlocks: new PromptBlocksPG(domainConfig),
|
|
8718
|
+
scorerDefinitions: new ScorerDefinitionsPG(domainConfig)
|
|
6940
8719
|
};
|
|
6941
8720
|
} catch (e) {
|
|
6942
8721
|
throw new MastraError(
|
|
@@ -7125,6 +8904,6 @@ Example Complex Query:
|
|
|
7125
8904
|
]
|
|
7126
8905
|
}`;
|
|
7127
8906
|
|
|
7128
|
-
export { AgentsPG, MemoryPG, ObservabilityPG, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, ScoresPG, WorkflowsPG, exportSchemas };
|
|
8907
|
+
export { AgentsPG, MemoryPG, ObservabilityPG, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PromptBlocksPG, ScorerDefinitionsPG, ScoresPG, WorkflowsPG, exportSchemas };
|
|
7129
8908
|
//# sourceMappingURL=index.js.map
|
|
7130
8909
|
//# sourceMappingURL=index.js.map
|