@mastra/pg 1.1.0 → 1.2.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 +178 -0
- package/dist/docs/README.md +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/SOURCE_MAP.json +1 -1
- package/dist/docs/memory/01-storage.md +10 -0
- package/dist/docs/rag/02-vector-databases.md +10 -1
- package/dist/index.cjs +787 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +787 -24
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/agents/index.d.ts +2 -1
- package/dist/storage/domains/agents/index.d.ts.map +1 -1
- package/dist/storage/domains/memory/index.d.ts +15 -2
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -3370,20 +3370,24 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
|
|
|
3370
3370
|
changedFields: Object.keys(snapshotConfig),
|
|
3371
3371
|
changeMessage: "Initial version"
|
|
3372
3372
|
});
|
|
3373
|
-
await this.#db.client.none(
|
|
3374
|
-
`UPDATE ${agentsTable} SET "activeVersionId" = $1, status = $2, "updatedAt" = $3, "updatedAtZ" = $4 WHERE id = $5`,
|
|
3375
|
-
[versionId, "published", nowIso, nowIso, agent.id]
|
|
3376
|
-
);
|
|
3377
3373
|
return {
|
|
3378
3374
|
id: agent.id,
|
|
3379
|
-
status: "
|
|
3380
|
-
activeVersionId:
|
|
3375
|
+
status: "draft",
|
|
3376
|
+
activeVersionId: void 0,
|
|
3381
3377
|
authorId: agent.authorId,
|
|
3382
3378
|
metadata: agent.metadata,
|
|
3383
3379
|
createdAt: now,
|
|
3384
3380
|
updatedAt: now
|
|
3385
3381
|
};
|
|
3386
3382
|
} catch (error$1) {
|
|
3383
|
+
try {
|
|
3384
|
+
const agentsTable = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3385
|
+
await this.#db.client.none(
|
|
3386
|
+
`DELETE FROM ${agentsTable} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
|
|
3387
|
+
[agent.id]
|
|
3388
|
+
);
|
|
3389
|
+
} catch {
|
|
3390
|
+
}
|
|
3387
3391
|
throw new error.MastraError(
|
|
3388
3392
|
{
|
|
3389
3393
|
id: storage.createStorageErrorId("PG", "CREATE_AGENT", "FAILED"),
|
|
@@ -3408,23 +3412,77 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
|
|
|
3408
3412
|
details: { agentId: id }
|
|
3409
3413
|
});
|
|
3410
3414
|
}
|
|
3415
|
+
const { authorId, activeVersionId, metadata, ...configFields } = updates;
|
|
3416
|
+
const configFieldNames = [
|
|
3417
|
+
"name",
|
|
3418
|
+
"description",
|
|
3419
|
+
"instructions",
|
|
3420
|
+
"model",
|
|
3421
|
+
"tools",
|
|
3422
|
+
"defaultOptions",
|
|
3423
|
+
"workflows",
|
|
3424
|
+
"agents",
|
|
3425
|
+
"integrationTools",
|
|
3426
|
+
"inputProcessors",
|
|
3427
|
+
"outputProcessors",
|
|
3428
|
+
"memory",
|
|
3429
|
+
"scorers"
|
|
3430
|
+
];
|
|
3431
|
+
const hasConfigUpdate = configFieldNames.some((field) => field in configFields);
|
|
3432
|
+
if (hasConfigUpdate) {
|
|
3433
|
+
const latestVersion = await this.getLatestVersion(id);
|
|
3434
|
+
if (!latestVersion) {
|
|
3435
|
+
throw new error.MastraError({
|
|
3436
|
+
id: storage.createStorageErrorId("PG", "UPDATE_AGENT", "NO_VERSIONS"),
|
|
3437
|
+
domain: error.ErrorDomain.STORAGE,
|
|
3438
|
+
category: error.ErrorCategory.SYSTEM,
|
|
3439
|
+
text: `No versions found for agent ${id}`,
|
|
3440
|
+
details: { agentId: id }
|
|
3441
|
+
});
|
|
3442
|
+
}
|
|
3443
|
+
const {
|
|
3444
|
+
id: _versionId,
|
|
3445
|
+
agentId: _agentId,
|
|
3446
|
+
versionNumber: _versionNumber,
|
|
3447
|
+
changedFields: _changedFields,
|
|
3448
|
+
changeMessage: _changeMessage,
|
|
3449
|
+
createdAt: _createdAt,
|
|
3450
|
+
...latestConfig
|
|
3451
|
+
} = latestVersion;
|
|
3452
|
+
const newConfig = {
|
|
3453
|
+
...latestConfig,
|
|
3454
|
+
...configFields
|
|
3455
|
+
};
|
|
3456
|
+
const changedFields = configFieldNames.filter(
|
|
3457
|
+
(field) => field in configFields && configFields[field] !== latestConfig[field]
|
|
3458
|
+
);
|
|
3459
|
+
if (changedFields.length > 0) {
|
|
3460
|
+
const newVersionId = crypto.randomUUID();
|
|
3461
|
+
const newVersionNumber = latestVersion.versionNumber + 1;
|
|
3462
|
+
await this.createVersion({
|
|
3463
|
+
id: newVersionId,
|
|
3464
|
+
agentId: id,
|
|
3465
|
+
versionNumber: newVersionNumber,
|
|
3466
|
+
...newConfig,
|
|
3467
|
+
changedFields,
|
|
3468
|
+
changeMessage: `Updated ${changedFields.join(", ")}`
|
|
3469
|
+
});
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3411
3472
|
const setClauses = [];
|
|
3412
3473
|
const values = [];
|
|
3413
3474
|
let paramIndex = 1;
|
|
3414
|
-
if (
|
|
3475
|
+
if (authorId !== void 0) {
|
|
3415
3476
|
setClauses.push(`"authorId" = $${paramIndex++}`);
|
|
3416
|
-
values.push(
|
|
3477
|
+
values.push(authorId);
|
|
3417
3478
|
}
|
|
3418
|
-
if (
|
|
3479
|
+
if (activeVersionId !== void 0) {
|
|
3419
3480
|
setClauses.push(`"activeVersionId" = $${paramIndex++}`);
|
|
3420
|
-
values.push(
|
|
3421
|
-
setClauses.push(`status = $${paramIndex++}`);
|
|
3422
|
-
values.push("published");
|
|
3481
|
+
values.push(activeVersionId);
|
|
3423
3482
|
}
|
|
3424
|
-
if (
|
|
3425
|
-
const mergedMetadata = { ...existingAgent.metadata, ...updates.metadata };
|
|
3483
|
+
if (metadata !== void 0) {
|
|
3426
3484
|
setClauses.push(`metadata = $${paramIndex++}`);
|
|
3427
|
-
values.push(JSON.stringify(
|
|
3485
|
+
values.push(JSON.stringify(metadata));
|
|
3428
3486
|
}
|
|
3429
3487
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3430
3488
|
setClauses.push(`"updatedAt" = $${paramIndex++}`);
|
|
@@ -3534,6 +3592,124 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
|
|
|
3534
3592
|
);
|
|
3535
3593
|
}
|
|
3536
3594
|
}
|
|
3595
|
+
async listAgentsResolved(args) {
|
|
3596
|
+
const { page = 0, perPage: perPageInput, orderBy } = args || {};
|
|
3597
|
+
const { field, direction } = this.parseOrderBy(orderBy);
|
|
3598
|
+
if (page < 0) {
|
|
3599
|
+
throw new error.MastraError(
|
|
3600
|
+
{
|
|
3601
|
+
id: storage.createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
|
|
3602
|
+
domain: error.ErrorDomain.STORAGE,
|
|
3603
|
+
category: error.ErrorCategory.USER,
|
|
3604
|
+
details: { page }
|
|
3605
|
+
},
|
|
3606
|
+
new Error("page must be >= 0")
|
|
3607
|
+
);
|
|
3608
|
+
}
|
|
3609
|
+
const perPage = storage.normalizePerPage(perPageInput, 100);
|
|
3610
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
3611
|
+
try {
|
|
3612
|
+
const agentsTableName = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
|
|
3613
|
+
const versionsTableName = getTableName2({
|
|
3614
|
+
indexName: storage.TABLE_AGENT_VERSIONS,
|
|
3615
|
+
schemaName: getSchemaName2(this.#schema)
|
|
3616
|
+
});
|
|
3617
|
+
const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${agentsTableName}`);
|
|
3618
|
+
const total = parseInt(countResult.count, 10);
|
|
3619
|
+
if (total === 0) {
|
|
3620
|
+
return {
|
|
3621
|
+
agents: [],
|
|
3622
|
+
total: 0,
|
|
3623
|
+
page,
|
|
3624
|
+
perPage: perPageForResponse,
|
|
3625
|
+
hasMore: false
|
|
3626
|
+
};
|
|
3627
|
+
}
|
|
3628
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
3629
|
+
const query = `
|
|
3630
|
+
WITH latest_versions AS (
|
|
3631
|
+
SELECT v.*
|
|
3632
|
+
FROM ${versionsTableName} v
|
|
3633
|
+
INNER JOIN (
|
|
3634
|
+
SELECT "agentId", MAX("versionNumber") as max_version
|
|
3635
|
+
FROM ${versionsTableName}
|
|
3636
|
+
GROUP BY "agentId"
|
|
3637
|
+
) lv ON v."agentId" = lv."agentId" AND v."versionNumber" = lv.max_version
|
|
3638
|
+
)
|
|
3639
|
+
SELECT
|
|
3640
|
+
a.*,
|
|
3641
|
+
COALESCE(av.id, lv.id) as version_id,
|
|
3642
|
+
COALESCE(av."versionNumber", lv."versionNumber") as version_number,
|
|
3643
|
+
COALESCE(av.name, lv.name) as version_name,
|
|
3644
|
+
COALESCE(av.description, lv.description) as version_description,
|
|
3645
|
+
COALESCE(av.instructions, lv.instructions) as version_instructions,
|
|
3646
|
+
COALESCE(av.model, lv.model) as version_model,
|
|
3647
|
+
COALESCE(av.tools, lv.tools) as version_tools,
|
|
3648
|
+
COALESCE(av."defaultOptions", lv."defaultOptions") as version_defaultOptions,
|
|
3649
|
+
COALESCE(av.workflows, lv.workflows) as version_workflows,
|
|
3650
|
+
COALESCE(av.agents, lv.agents) as version_agents,
|
|
3651
|
+
COALESCE(av."integrationTools", lv."integrationTools") as version_integrationTools,
|
|
3652
|
+
COALESCE(av."inputProcessors", lv."inputProcessors") as version_inputProcessors,
|
|
3653
|
+
COALESCE(av."outputProcessors", lv."outputProcessors") as version_outputProcessors,
|
|
3654
|
+
COALESCE(av.memory, lv.memory) as version_memory,
|
|
3655
|
+
COALESCE(av.scorers, lv.scorers) as version_scorers
|
|
3656
|
+
FROM ${agentsTableName} a
|
|
3657
|
+
LEFT JOIN ${versionsTableName} av ON a."activeVersionId" = av.id
|
|
3658
|
+
LEFT JOIN latest_versions lv ON a.id = lv."agentId"
|
|
3659
|
+
ORDER BY a."${field}" ${direction}
|
|
3660
|
+
LIMIT $1 OFFSET $2
|
|
3661
|
+
`;
|
|
3662
|
+
const dataResult = await this.#db.client.manyOrNone(query, [limitValue, offset]);
|
|
3663
|
+
const resolvedAgents = (dataResult || []).map((row) => {
|
|
3664
|
+
const agent = this.parseRow({
|
|
3665
|
+
id: row.id,
|
|
3666
|
+
status: row.status,
|
|
3667
|
+
activeVersionId: row.activeVersionId,
|
|
3668
|
+
authorId: row.authorId,
|
|
3669
|
+
metadata: row.metadata,
|
|
3670
|
+
createdAt: row.createdAt,
|
|
3671
|
+
createdAtZ: row.createdAtZ,
|
|
3672
|
+
updatedAt: row.updatedAt,
|
|
3673
|
+
updatedAtZ: row.updatedAtZ
|
|
3674
|
+
});
|
|
3675
|
+
if (row.version_id) {
|
|
3676
|
+
return {
|
|
3677
|
+
...agent,
|
|
3678
|
+
name: row.version_name,
|
|
3679
|
+
description: row.version_description,
|
|
3680
|
+
instructions: row.version_instructions,
|
|
3681
|
+
model: this.parseJson(row.version_model, "model"),
|
|
3682
|
+
tools: this.parseJson(row.version_tools, "tools"),
|
|
3683
|
+
defaultOptions: this.parseJson(row.version_defaultOptions, "defaultOptions"),
|
|
3684
|
+
workflows: this.parseJson(row.version_workflows, "workflows"),
|
|
3685
|
+
agents: this.parseJson(row.version_agents, "agents"),
|
|
3686
|
+
integrationTools: this.parseJson(row.version_integrationTools, "integrationTools"),
|
|
3687
|
+
inputProcessors: this.parseJson(row.version_inputProcessors, "inputProcessors"),
|
|
3688
|
+
outputProcessors: this.parseJson(row.version_outputProcessors, "outputProcessors"),
|
|
3689
|
+
memory: this.parseJson(row.version_memory, "memory"),
|
|
3690
|
+
scorers: this.parseJson(row.version_scorers, "scorers")
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
return agent;
|
|
3694
|
+
});
|
|
3695
|
+
return {
|
|
3696
|
+
agents: resolvedAgents,
|
|
3697
|
+
total,
|
|
3698
|
+
page,
|
|
3699
|
+
perPage: perPageForResponse,
|
|
3700
|
+
hasMore: perPageInput === false ? false : offset + perPage < total
|
|
3701
|
+
};
|
|
3702
|
+
} catch (error$1) {
|
|
3703
|
+
throw new error.MastraError(
|
|
3704
|
+
{
|
|
3705
|
+
id: storage.createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "FAILED"),
|
|
3706
|
+
domain: error.ErrorDomain.STORAGE,
|
|
3707
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
3708
|
+
},
|
|
3709
|
+
error$1
|
|
3710
|
+
);
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3537
3713
|
// ==========================================================================
|
|
3538
3714
|
// Agent Version Methods
|
|
3539
3715
|
// ==========================================================================
|
|
@@ -3790,6 +3966,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
|
|
|
3790
3966
|
};
|
|
3791
3967
|
}
|
|
3792
3968
|
};
|
|
3969
|
+
var OM_TABLE = "mastra_observational_memory";
|
|
3793
3970
|
function getSchemaName3(schema) {
|
|
3794
3971
|
return schema ? `"${schema}"` : '"public"';
|
|
3795
3972
|
}
|
|
@@ -3801,12 +3978,13 @@ function inPlaceholders(count, startIndex = 1) {
|
|
|
3801
3978
|
return Array.from({ length: count }, (_, i) => `$${i + startIndex}`).join(", ");
|
|
3802
3979
|
}
|
|
3803
3980
|
var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
3981
|
+
supportsObservationalMemory = true;
|
|
3804
3982
|
#db;
|
|
3805
3983
|
#schema;
|
|
3806
3984
|
#skipDefaultIndexes;
|
|
3807
3985
|
#indexes;
|
|
3808
3986
|
/** Tables managed by this domain */
|
|
3809
|
-
static MANAGED_TABLES = [storage.TABLE_THREADS, storage.TABLE_MESSAGES, storage.TABLE_RESOURCES];
|
|
3987
|
+
static MANAGED_TABLES = [storage.TABLE_THREADS, storage.TABLE_MESSAGES, storage.TABLE_RESOURCES, OM_TABLE];
|
|
3810
3988
|
constructor(config) {
|
|
3811
3989
|
super();
|
|
3812
3990
|
const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
|
|
@@ -3819,11 +3997,30 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
3819
3997
|
await this.#db.createTable({ tableName: storage.TABLE_THREADS, schema: storage.TABLE_SCHEMAS[storage.TABLE_THREADS] });
|
|
3820
3998
|
await this.#db.createTable({ tableName: storage.TABLE_MESSAGES, schema: storage.TABLE_SCHEMAS[storage.TABLE_MESSAGES] });
|
|
3821
3999
|
await this.#db.createTable({ tableName: storage.TABLE_RESOURCES, schema: storage.TABLE_SCHEMAS[storage.TABLE_RESOURCES] });
|
|
4000
|
+
let omSchema;
|
|
4001
|
+
try {
|
|
4002
|
+
const { OBSERVATIONAL_MEMORY_TABLE_SCHEMA } = await import('@mastra/core/storage');
|
|
4003
|
+
omSchema = OBSERVATIONAL_MEMORY_TABLE_SCHEMA?.[OM_TABLE];
|
|
4004
|
+
} catch {
|
|
4005
|
+
}
|
|
4006
|
+
if (omSchema) {
|
|
4007
|
+
await this.#db.createTable({
|
|
4008
|
+
tableName: OM_TABLE,
|
|
4009
|
+
schema: omSchema
|
|
4010
|
+
});
|
|
4011
|
+
}
|
|
3822
4012
|
await this.#db.alterTable({
|
|
3823
4013
|
tableName: storage.TABLE_MESSAGES,
|
|
3824
4014
|
schema: storage.TABLE_SCHEMAS[storage.TABLE_MESSAGES],
|
|
3825
4015
|
ifNotExists: ["resourceId"]
|
|
3826
4016
|
});
|
|
4017
|
+
if (omSchema) {
|
|
4018
|
+
const omTableName = getTableName3({
|
|
4019
|
+
indexName: OM_TABLE,
|
|
4020
|
+
schemaName: getSchemaName3(this.#schema)
|
|
4021
|
+
});
|
|
4022
|
+
await this.#db.client.none(`CREATE INDEX IF NOT EXISTS idx_om_lookup_key ON ${omTableName} ("lookupKey")`);
|
|
4023
|
+
}
|
|
3827
4024
|
await this.createDefaultIndexes();
|
|
3828
4025
|
await this.createCustomIndexes();
|
|
3829
4026
|
}
|
|
@@ -4198,8 +4395,8 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4198
4395
|
SELECT ${selectColumns}
|
|
4199
4396
|
FROM ${tableName} m
|
|
4200
4397
|
WHERE m.thread_id = (SELECT thread_id FROM ${tableName} WHERE id = $${paramIdx})
|
|
4201
|
-
AND m."createdAt" <= (SELECT "createdAt" FROM ${tableName} WHERE id = $${paramIdx})
|
|
4202
|
-
ORDER BY m."createdAt" DESC
|
|
4398
|
+
AND COALESCE(m."createdAtZ", m."createdAt") <= (SELECT COALESCE("createdAtZ", "createdAt") FROM ${tableName} WHERE id = $${paramIdx})
|
|
4399
|
+
ORDER BY COALESCE(m."createdAtZ", m."createdAt") DESC
|
|
4203
4400
|
LIMIT $${paramIdx + 1}
|
|
4204
4401
|
)`);
|
|
4205
4402
|
params.push(id, withPreviousMessages + 1);
|
|
@@ -4209,8 +4406,8 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4209
4406
|
SELECT ${selectColumns}
|
|
4210
4407
|
FROM ${tableName} m
|
|
4211
4408
|
WHERE m.thread_id = (SELECT thread_id FROM ${tableName} WHERE id = $${paramIdx})
|
|
4212
|
-
AND m."createdAt" > (SELECT "createdAt" FROM ${tableName} WHERE id = $${paramIdx})
|
|
4213
|
-
ORDER BY m."createdAt" ASC
|
|
4409
|
+
AND COALESCE(m."createdAtZ", m."createdAt") > (SELECT COALESCE("createdAtZ", "createdAt") FROM ${tableName} WHERE id = $${paramIdx})
|
|
4410
|
+
ORDER BY COALESCE(m."createdAtZ", m."createdAt") ASC
|
|
4214
4411
|
LIMIT $${paramIdx + 1}
|
|
4215
4412
|
)`);
|
|
4216
4413
|
params.push(id, withNextMessages);
|
|
@@ -4327,12 +4524,12 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4327
4524
|
}
|
|
4328
4525
|
if (filter?.dateRange?.start) {
|
|
4329
4526
|
const startOp = filter.dateRange.startExclusive ? ">" : ">=";
|
|
4330
|
-
conditions.push(`"createdAt" ${startOp} $${paramIndex++}`);
|
|
4527
|
+
conditions.push(`COALESCE("createdAtZ", "createdAt") ${startOp} $${paramIndex++}`);
|
|
4331
4528
|
queryParams.push(filter.dateRange.start);
|
|
4332
4529
|
}
|
|
4333
4530
|
if (filter?.dateRange?.end) {
|
|
4334
4531
|
const endOp = filter.dateRange.endExclusive ? "<" : "<=";
|
|
4335
|
-
conditions.push(`"createdAt" ${endOp} $${paramIndex++}`);
|
|
4532
|
+
conditions.push(`COALESCE("createdAtZ", "createdAt") ${endOp} $${paramIndex++}`);
|
|
4336
4533
|
queryParams.push(filter.dateRange.end);
|
|
4337
4534
|
}
|
|
4338
4535
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
@@ -4418,6 +4615,133 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4418
4615
|
};
|
|
4419
4616
|
}
|
|
4420
4617
|
}
|
|
4618
|
+
async listMessagesByResourceId(args) {
|
|
4619
|
+
const { resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
|
|
4620
|
+
const hasResourceId = resourceId !== void 0 && resourceId !== null && resourceId.trim() !== "";
|
|
4621
|
+
if (!hasResourceId) {
|
|
4622
|
+
throw new error.MastraError(
|
|
4623
|
+
{
|
|
4624
|
+
id: storage.createStorageErrorId("PG", "LIST_MESSAGES_BY_RESOURCE_ID", "INVALID_QUERY"),
|
|
4625
|
+
domain: error.ErrorDomain.STORAGE,
|
|
4626
|
+
category: error.ErrorCategory.USER,
|
|
4627
|
+
details: {
|
|
4628
|
+
resourceId: resourceId ?? ""
|
|
4629
|
+
}
|
|
4630
|
+
},
|
|
4631
|
+
new Error("resourceId is required")
|
|
4632
|
+
);
|
|
4633
|
+
}
|
|
4634
|
+
if (page < 0) {
|
|
4635
|
+
throw new error.MastraError({
|
|
4636
|
+
id: storage.createStorageErrorId("PG", "LIST_MESSAGES_BY_RESOURCE_ID", "INVALID_PAGE"),
|
|
4637
|
+
domain: error.ErrorDomain.STORAGE,
|
|
4638
|
+
category: error.ErrorCategory.USER,
|
|
4639
|
+
text: "Page number must be non-negative",
|
|
4640
|
+
details: {
|
|
4641
|
+
resourceId,
|
|
4642
|
+
page
|
|
4643
|
+
}
|
|
4644
|
+
});
|
|
4645
|
+
}
|
|
4646
|
+
const perPage = storage.normalizePerPage(perPageInput, 40);
|
|
4647
|
+
const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
|
|
4648
|
+
try {
|
|
4649
|
+
const { field, direction } = this.parseOrderBy(orderBy, "ASC");
|
|
4650
|
+
const orderByStatement = `ORDER BY "${field}" ${direction}`;
|
|
4651
|
+
const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
|
|
4652
|
+
const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
|
|
4653
|
+
const conditions = [];
|
|
4654
|
+
const queryParams = [];
|
|
4655
|
+
let paramIndex = 1;
|
|
4656
|
+
conditions.push(`"resourceId" = $${paramIndex++}`);
|
|
4657
|
+
queryParams.push(resourceId);
|
|
4658
|
+
if (filter?.dateRange?.start) {
|
|
4659
|
+
const startOp = filter.dateRange.startExclusive ? ">" : ">=";
|
|
4660
|
+
conditions.push(`"createdAt" ${startOp} $${paramIndex++}`);
|
|
4661
|
+
queryParams.push(filter.dateRange.start);
|
|
4662
|
+
}
|
|
4663
|
+
if (filter?.dateRange?.end) {
|
|
4664
|
+
const endOp = filter.dateRange.endExclusive ? "<" : "<=";
|
|
4665
|
+
conditions.push(`"createdAt" ${endOp} $${paramIndex++}`);
|
|
4666
|
+
queryParams.push(filter.dateRange.end);
|
|
4667
|
+
}
|
|
4668
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
4669
|
+
const countQuery = `SELECT COUNT(*) FROM ${tableName} ${whereClause}`;
|
|
4670
|
+
const countResult = await this.#db.client.one(countQuery, queryParams);
|
|
4671
|
+
const total = parseInt(countResult.count, 10);
|
|
4672
|
+
const limitValue = perPageInput === false ? total : perPage;
|
|
4673
|
+
const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
|
|
4674
|
+
const rows = await this.#db.client.manyOrNone(dataQuery, [...queryParams, limitValue, offset]);
|
|
4675
|
+
const messages = [...rows || []];
|
|
4676
|
+
if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
|
|
4677
|
+
return {
|
|
4678
|
+
messages: [],
|
|
4679
|
+
total: 0,
|
|
4680
|
+
page,
|
|
4681
|
+
perPage: perPageForResponse,
|
|
4682
|
+
hasMore: false
|
|
4683
|
+
};
|
|
4684
|
+
}
|
|
4685
|
+
const messageIds = new Set(messages.map((m) => m.id));
|
|
4686
|
+
if (include && include.length > 0) {
|
|
4687
|
+
const includeMessages = await this._getIncludedMessages({ include });
|
|
4688
|
+
if (includeMessages) {
|
|
4689
|
+
for (const includeMsg of includeMessages) {
|
|
4690
|
+
if (!messageIds.has(includeMsg.id)) {
|
|
4691
|
+
messages.push(includeMsg);
|
|
4692
|
+
messageIds.add(includeMsg.id);
|
|
4693
|
+
}
|
|
4694
|
+
}
|
|
4695
|
+
}
|
|
4696
|
+
}
|
|
4697
|
+
const messagesWithParsedContent = messages.map((row) => this.parseRow(row));
|
|
4698
|
+
const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
|
|
4699
|
+
let finalMessages = list.get.all.db();
|
|
4700
|
+
finalMessages = finalMessages.sort((a, b) => {
|
|
4701
|
+
const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
|
|
4702
|
+
const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
|
|
4703
|
+
if (aValue == null && bValue == null) return a.id.localeCompare(b.id);
|
|
4704
|
+
if (aValue == null) return 1;
|
|
4705
|
+
if (bValue == null) return -1;
|
|
4706
|
+
if (aValue === bValue) {
|
|
4707
|
+
return a.id.localeCompare(b.id);
|
|
4708
|
+
}
|
|
4709
|
+
if (typeof aValue === "number" && typeof bValue === "number") {
|
|
4710
|
+
return direction === "ASC" ? aValue - bValue : bValue - aValue;
|
|
4711
|
+
}
|
|
4712
|
+
return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
|
|
4713
|
+
});
|
|
4714
|
+
const hasMore = perPageInput !== false && offset + perPage < total;
|
|
4715
|
+
return {
|
|
4716
|
+
messages: finalMessages,
|
|
4717
|
+
total,
|
|
4718
|
+
page,
|
|
4719
|
+
perPage: perPageForResponse,
|
|
4720
|
+
hasMore
|
|
4721
|
+
};
|
|
4722
|
+
} catch (error$1) {
|
|
4723
|
+
const mastraError = new error.MastraError(
|
|
4724
|
+
{
|
|
4725
|
+
id: storage.createStorageErrorId("PG", "LIST_MESSAGES_BY_RESOURCE_ID", "FAILED"),
|
|
4726
|
+
domain: error.ErrorDomain.STORAGE,
|
|
4727
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
4728
|
+
details: {
|
|
4729
|
+
resourceId: resourceId ?? ""
|
|
4730
|
+
}
|
|
4731
|
+
},
|
|
4732
|
+
error$1
|
|
4733
|
+
);
|
|
4734
|
+
this.logger?.error?.(mastraError.toString());
|
|
4735
|
+
this.logger?.trackException(mastraError);
|
|
4736
|
+
return {
|
|
4737
|
+
messages: [],
|
|
4738
|
+
total: 0,
|
|
4739
|
+
page,
|
|
4740
|
+
perPage: perPageForResponse,
|
|
4741
|
+
hasMore: false
|
|
4742
|
+
};
|
|
4743
|
+
}
|
|
4744
|
+
}
|
|
4421
4745
|
async saveMessages({ messages }) {
|
|
4422
4746
|
if (messages.length === 0) return { messages: [] };
|
|
4423
4747
|
const threadId = messages[0]?.threadId;
|
|
@@ -4749,11 +5073,11 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4749
5073
|
const messageParams = [sourceThreadId];
|
|
4750
5074
|
let paramIndex = 2;
|
|
4751
5075
|
if (options?.messageFilter?.startDate) {
|
|
4752
|
-
messageQuery += ` AND "createdAt" >= $${paramIndex++}`;
|
|
5076
|
+
messageQuery += ` AND COALESCE("createdAtZ", "createdAt") >= $${paramIndex++}`;
|
|
4753
5077
|
messageParams.push(options.messageFilter.startDate);
|
|
4754
5078
|
}
|
|
4755
5079
|
if (options?.messageFilter?.endDate) {
|
|
4756
|
-
messageQuery += ` AND "createdAt" <= $${paramIndex++}`;
|
|
5080
|
+
messageQuery += ` AND COALESCE("createdAtZ", "createdAt") <= $${paramIndex++}`;
|
|
4757
5081
|
messageParams.push(options.messageFilter.endDate);
|
|
4758
5082
|
}
|
|
4759
5083
|
if (options?.messageFilter?.messageIds && options.messageFilter.messageIds.length > 0) {
|
|
@@ -4861,6 +5185,445 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
|
|
|
4861
5185
|
);
|
|
4862
5186
|
}
|
|
4863
5187
|
}
|
|
5188
|
+
// ============================================
|
|
5189
|
+
// Observational Memory Methods
|
|
5190
|
+
// ============================================
|
|
5191
|
+
getOMKey(threadId, resourceId) {
|
|
5192
|
+
return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
|
|
5193
|
+
}
|
|
5194
|
+
parseOMRow(row) {
|
|
5195
|
+
return {
|
|
5196
|
+
id: row.id,
|
|
5197
|
+
scope: row.scope,
|
|
5198
|
+
threadId: row.threadId || null,
|
|
5199
|
+
resourceId: row.resourceId,
|
|
5200
|
+
createdAt: new Date(row.createdAtZ),
|
|
5201
|
+
updatedAt: new Date(row.updatedAtZ),
|
|
5202
|
+
lastObservedAt: row.lastObservedAtZ ? new Date(row.lastObservedAtZ) : void 0,
|
|
5203
|
+
originType: row.originType || "initial",
|
|
5204
|
+
generationCount: Number(row.generationCount || 0),
|
|
5205
|
+
activeObservations: row.activeObservations || "",
|
|
5206
|
+
bufferedObservations: row.activeObservationsPendingUpdate || void 0,
|
|
5207
|
+
totalTokensObserved: Number(row.totalTokensObserved || 0),
|
|
5208
|
+
observationTokenCount: Number(row.observationTokenCount || 0),
|
|
5209
|
+
pendingMessageTokens: Number(row.pendingMessageTokens || 0),
|
|
5210
|
+
isReflecting: Boolean(row.isReflecting),
|
|
5211
|
+
isObserving: Boolean(row.isObserving),
|
|
5212
|
+
config: row.config ? typeof row.config === "string" ? JSON.parse(row.config) : row.config : {},
|
|
5213
|
+
metadata: row.metadata ? typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata : void 0,
|
|
5214
|
+
observedMessageIds: row.observedMessageIds ? typeof row.observedMessageIds === "string" ? JSON.parse(row.observedMessageIds) : row.observedMessageIds : void 0,
|
|
5215
|
+
observedTimezone: row.observedTimezone || void 0
|
|
5216
|
+
};
|
|
5217
|
+
}
|
|
5218
|
+
async getObservationalMemory(threadId, resourceId) {
|
|
5219
|
+
try {
|
|
5220
|
+
const lookupKey = this.getOMKey(threadId, resourceId);
|
|
5221
|
+
const tableName = getTableName3({
|
|
5222
|
+
indexName: OM_TABLE,
|
|
5223
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5224
|
+
});
|
|
5225
|
+
const result = await this.#db.client.oneOrNone(
|
|
5226
|
+
`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`,
|
|
5227
|
+
[lookupKey]
|
|
5228
|
+
);
|
|
5229
|
+
if (!result) return null;
|
|
5230
|
+
return this.parseOMRow(result);
|
|
5231
|
+
} catch (error$1) {
|
|
5232
|
+
throw new error.MastraError(
|
|
5233
|
+
{
|
|
5234
|
+
id: storage.createStorageErrorId("PG", "GET_OBSERVATIONAL_MEMORY", "FAILED"),
|
|
5235
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5236
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5237
|
+
details: { threadId, resourceId }
|
|
5238
|
+
},
|
|
5239
|
+
error$1
|
|
5240
|
+
);
|
|
5241
|
+
}
|
|
5242
|
+
}
|
|
5243
|
+
async getObservationalMemoryHistory(threadId, resourceId, limit = 10) {
|
|
5244
|
+
try {
|
|
5245
|
+
const lookupKey = this.getOMKey(threadId, resourceId);
|
|
5246
|
+
const tableName = getTableName3({
|
|
5247
|
+
indexName: OM_TABLE,
|
|
5248
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5249
|
+
});
|
|
5250
|
+
const result = await this.#db.client.manyOrNone(
|
|
5251
|
+
`SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT $2`,
|
|
5252
|
+
[lookupKey, limit]
|
|
5253
|
+
);
|
|
5254
|
+
if (!result) return [];
|
|
5255
|
+
return result.map((row) => this.parseOMRow(row));
|
|
5256
|
+
} catch (error$1) {
|
|
5257
|
+
throw new error.MastraError(
|
|
5258
|
+
{
|
|
5259
|
+
id: storage.createStorageErrorId("PG", "GET_OBSERVATIONAL_MEMORY_HISTORY", "FAILED"),
|
|
5260
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5261
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5262
|
+
details: { threadId, resourceId, limit }
|
|
5263
|
+
},
|
|
5264
|
+
error$1
|
|
5265
|
+
);
|
|
5266
|
+
}
|
|
5267
|
+
}
|
|
5268
|
+
async initializeObservationalMemory(input) {
|
|
5269
|
+
try {
|
|
5270
|
+
const id = crypto.randomUUID();
|
|
5271
|
+
const now = /* @__PURE__ */ new Date();
|
|
5272
|
+
const lookupKey = this.getOMKey(input.threadId, input.resourceId);
|
|
5273
|
+
const record = {
|
|
5274
|
+
id,
|
|
5275
|
+
scope: input.scope,
|
|
5276
|
+
threadId: input.threadId,
|
|
5277
|
+
resourceId: input.resourceId,
|
|
5278
|
+
createdAt: now,
|
|
5279
|
+
updatedAt: now,
|
|
5280
|
+
lastObservedAt: void 0,
|
|
5281
|
+
originType: "initial",
|
|
5282
|
+
generationCount: 0,
|
|
5283
|
+
activeObservations: "",
|
|
5284
|
+
totalTokensObserved: 0,
|
|
5285
|
+
observationTokenCount: 0,
|
|
5286
|
+
pendingMessageTokens: 0,
|
|
5287
|
+
isReflecting: false,
|
|
5288
|
+
isObserving: false,
|
|
5289
|
+
config: input.config,
|
|
5290
|
+
observedTimezone: input.observedTimezone
|
|
5291
|
+
};
|
|
5292
|
+
const tableName = getTableName3({
|
|
5293
|
+
indexName: OM_TABLE,
|
|
5294
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5295
|
+
});
|
|
5296
|
+
const nowStr = now.toISOString();
|
|
5297
|
+
await this.#db.client.none(
|
|
5298
|
+
`INSERT INTO ${tableName} (
|
|
5299
|
+
id, "lookupKey", scope, "resourceId", "threadId",
|
|
5300
|
+
"activeObservations", "activeObservationsPendingUpdate",
|
|
5301
|
+
"originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
|
|
5302
|
+
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
5303
|
+
"isObserving", "isReflecting", "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
5304
|
+
) 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)`,
|
|
5305
|
+
[
|
|
5306
|
+
id,
|
|
5307
|
+
lookupKey,
|
|
5308
|
+
input.scope,
|
|
5309
|
+
input.resourceId,
|
|
5310
|
+
input.threadId || null,
|
|
5311
|
+
"",
|
|
5312
|
+
null,
|
|
5313
|
+
"initial",
|
|
5314
|
+
JSON.stringify(input.config),
|
|
5315
|
+
0,
|
|
5316
|
+
null,
|
|
5317
|
+
// lastObservedAt
|
|
5318
|
+
null,
|
|
5319
|
+
// lastObservedAtZ
|
|
5320
|
+
null,
|
|
5321
|
+
// lastReflectionAt
|
|
5322
|
+
null,
|
|
5323
|
+
// lastReflectionAtZ
|
|
5324
|
+
0,
|
|
5325
|
+
0,
|
|
5326
|
+
0,
|
|
5327
|
+
false,
|
|
5328
|
+
false,
|
|
5329
|
+
input.observedTimezone || null,
|
|
5330
|
+
nowStr,
|
|
5331
|
+
// createdAt
|
|
5332
|
+
nowStr,
|
|
5333
|
+
// createdAtZ
|
|
5334
|
+
nowStr,
|
|
5335
|
+
// updatedAt
|
|
5336
|
+
nowStr
|
|
5337
|
+
// updatedAtZ
|
|
5338
|
+
]
|
|
5339
|
+
);
|
|
5340
|
+
return record;
|
|
5341
|
+
} catch (error$1) {
|
|
5342
|
+
throw new error.MastraError(
|
|
5343
|
+
{
|
|
5344
|
+
id: storage.createStorageErrorId("PG", "INITIALIZE_OBSERVATIONAL_MEMORY", "FAILED"),
|
|
5345
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5346
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5347
|
+
details: { threadId: input.threadId, resourceId: input.resourceId }
|
|
5348
|
+
},
|
|
5349
|
+
error$1
|
|
5350
|
+
);
|
|
5351
|
+
}
|
|
5352
|
+
}
|
|
5353
|
+
async updateActiveObservations(input) {
|
|
5354
|
+
try {
|
|
5355
|
+
const now = /* @__PURE__ */ new Date();
|
|
5356
|
+
const tableName = getTableName3({
|
|
5357
|
+
indexName: OM_TABLE,
|
|
5358
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5359
|
+
});
|
|
5360
|
+
const lastObservedAtStr = input.lastObservedAt.toISOString();
|
|
5361
|
+
const nowStr = now.toISOString();
|
|
5362
|
+
const observedMessageIdsJson = input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null;
|
|
5363
|
+
const result = await this.#db.client.query(
|
|
5364
|
+
`UPDATE ${tableName} SET
|
|
5365
|
+
"activeObservations" = $1,
|
|
5366
|
+
"lastObservedAt" = $2,
|
|
5367
|
+
"lastObservedAtZ" = $3,
|
|
5368
|
+
"pendingMessageTokens" = 0,
|
|
5369
|
+
"observationTokenCount" = $4,
|
|
5370
|
+
"totalTokensObserved" = "totalTokensObserved" + $5,
|
|
5371
|
+
"observedMessageIds" = $6,
|
|
5372
|
+
"updatedAt" = $7,
|
|
5373
|
+
"updatedAtZ" = $8
|
|
5374
|
+
WHERE id = $9`,
|
|
5375
|
+
[
|
|
5376
|
+
input.observations,
|
|
5377
|
+
lastObservedAtStr,
|
|
5378
|
+
lastObservedAtStr,
|
|
5379
|
+
input.tokenCount,
|
|
5380
|
+
input.tokenCount,
|
|
5381
|
+
observedMessageIdsJson,
|
|
5382
|
+
nowStr,
|
|
5383
|
+
nowStr,
|
|
5384
|
+
input.id
|
|
5385
|
+
]
|
|
5386
|
+
);
|
|
5387
|
+
if (result.rowCount === 0) {
|
|
5388
|
+
throw new error.MastraError({
|
|
5389
|
+
id: storage.createStorageErrorId("PG", "UPDATE_ACTIVE_OBSERVATIONS", "NOT_FOUND"),
|
|
5390
|
+
text: `Observational memory record not found: ${input.id}`,
|
|
5391
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5392
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5393
|
+
details: { id: input.id }
|
|
5394
|
+
});
|
|
5395
|
+
}
|
|
5396
|
+
} catch (error$1) {
|
|
5397
|
+
if (error$1 instanceof error.MastraError) {
|
|
5398
|
+
throw error$1;
|
|
5399
|
+
}
|
|
5400
|
+
throw new error.MastraError(
|
|
5401
|
+
{
|
|
5402
|
+
id: storage.createStorageErrorId("PG", "UPDATE_ACTIVE_OBSERVATIONS", "FAILED"),
|
|
5403
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5404
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5405
|
+
details: { id: input.id }
|
|
5406
|
+
},
|
|
5407
|
+
error$1
|
|
5408
|
+
);
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
5411
|
+
async createReflectionGeneration(input) {
|
|
5412
|
+
try {
|
|
5413
|
+
const id = crypto.randomUUID();
|
|
5414
|
+
const now = /* @__PURE__ */ new Date();
|
|
5415
|
+
const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
|
|
5416
|
+
const record = {
|
|
5417
|
+
id,
|
|
5418
|
+
scope: input.currentRecord.scope,
|
|
5419
|
+
threadId: input.currentRecord.threadId,
|
|
5420
|
+
resourceId: input.currentRecord.resourceId,
|
|
5421
|
+
createdAt: now,
|
|
5422
|
+
updatedAt: now,
|
|
5423
|
+
lastObservedAt: input.currentRecord.lastObservedAt,
|
|
5424
|
+
originType: "reflection",
|
|
5425
|
+
generationCount: input.currentRecord.generationCount + 1,
|
|
5426
|
+
activeObservations: input.reflection,
|
|
5427
|
+
totalTokensObserved: input.currentRecord.totalTokensObserved,
|
|
5428
|
+
observationTokenCount: input.tokenCount,
|
|
5429
|
+
pendingMessageTokens: 0,
|
|
5430
|
+
isReflecting: false,
|
|
5431
|
+
isObserving: false,
|
|
5432
|
+
config: input.currentRecord.config,
|
|
5433
|
+
metadata: input.currentRecord.metadata,
|
|
5434
|
+
observedTimezone: input.currentRecord.observedTimezone
|
|
5435
|
+
};
|
|
5436
|
+
const tableName = getTableName3({
|
|
5437
|
+
indexName: OM_TABLE,
|
|
5438
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5439
|
+
});
|
|
5440
|
+
const nowStr = now.toISOString();
|
|
5441
|
+
const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
|
|
5442
|
+
await this.#db.client.none(
|
|
5443
|
+
`INSERT INTO ${tableName} (
|
|
5444
|
+
id, "lookupKey", scope, "resourceId", "threadId",
|
|
5445
|
+
"activeObservations", "activeObservationsPendingUpdate",
|
|
5446
|
+
"originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
|
|
5447
|
+
"pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
|
|
5448
|
+
"isObserving", "isReflecting", "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
|
|
5449
|
+
) 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)`,
|
|
5450
|
+
[
|
|
5451
|
+
id,
|
|
5452
|
+
lookupKey,
|
|
5453
|
+
record.scope,
|
|
5454
|
+
record.resourceId,
|
|
5455
|
+
record.threadId || null,
|
|
5456
|
+
input.reflection,
|
|
5457
|
+
null,
|
|
5458
|
+
"reflection",
|
|
5459
|
+
JSON.stringify(record.config),
|
|
5460
|
+
input.currentRecord.generationCount + 1,
|
|
5461
|
+
lastObservedAtStr,
|
|
5462
|
+
// lastObservedAt
|
|
5463
|
+
lastObservedAtStr,
|
|
5464
|
+
// lastObservedAtZ
|
|
5465
|
+
nowStr,
|
|
5466
|
+
// lastReflectionAt
|
|
5467
|
+
nowStr,
|
|
5468
|
+
// lastReflectionAtZ
|
|
5469
|
+
record.pendingMessageTokens,
|
|
5470
|
+
record.totalTokensObserved,
|
|
5471
|
+
record.observationTokenCount,
|
|
5472
|
+
false,
|
|
5473
|
+
false,
|
|
5474
|
+
record.observedTimezone || null,
|
|
5475
|
+
nowStr,
|
|
5476
|
+
// createdAt
|
|
5477
|
+
nowStr,
|
|
5478
|
+
// createdAtZ
|
|
5479
|
+
nowStr,
|
|
5480
|
+
// updatedAt
|
|
5481
|
+
nowStr
|
|
5482
|
+
// updatedAtZ
|
|
5483
|
+
]
|
|
5484
|
+
);
|
|
5485
|
+
return record;
|
|
5486
|
+
} catch (error$1) {
|
|
5487
|
+
throw new error.MastraError(
|
|
5488
|
+
{
|
|
5489
|
+
id: storage.createStorageErrorId("PG", "CREATE_REFLECTION_GENERATION", "FAILED"),
|
|
5490
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5491
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5492
|
+
details: { currentRecordId: input.currentRecord.id }
|
|
5493
|
+
},
|
|
5494
|
+
error$1
|
|
5495
|
+
);
|
|
5496
|
+
}
|
|
5497
|
+
}
|
|
5498
|
+
async setReflectingFlag(id, isReflecting) {
|
|
5499
|
+
try {
|
|
5500
|
+
const tableName = getTableName3({
|
|
5501
|
+
indexName: OM_TABLE,
|
|
5502
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5503
|
+
});
|
|
5504
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5505
|
+
const result = await this.#db.client.query(
|
|
5506
|
+
`UPDATE ${tableName} SET "isReflecting" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`,
|
|
5507
|
+
[isReflecting, nowStr, nowStr, id]
|
|
5508
|
+
);
|
|
5509
|
+
if (result.rowCount === 0) {
|
|
5510
|
+
throw new error.MastraError({
|
|
5511
|
+
id: storage.createStorageErrorId("PG", "SET_REFLECTING_FLAG", "NOT_FOUND"),
|
|
5512
|
+
text: `Observational memory record not found: ${id}`,
|
|
5513
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5514
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5515
|
+
details: { id, isReflecting }
|
|
5516
|
+
});
|
|
5517
|
+
}
|
|
5518
|
+
} catch (error$1) {
|
|
5519
|
+
if (error$1 instanceof error.MastraError) {
|
|
5520
|
+
throw error$1;
|
|
5521
|
+
}
|
|
5522
|
+
throw new error.MastraError(
|
|
5523
|
+
{
|
|
5524
|
+
id: storage.createStorageErrorId("PG", "SET_REFLECTING_FLAG", "FAILED"),
|
|
5525
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5526
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5527
|
+
details: { id, isReflecting }
|
|
5528
|
+
},
|
|
5529
|
+
error$1
|
|
5530
|
+
);
|
|
5531
|
+
}
|
|
5532
|
+
}
|
|
5533
|
+
async setObservingFlag(id, isObserving) {
|
|
5534
|
+
try {
|
|
5535
|
+
const tableName = getTableName3({
|
|
5536
|
+
indexName: OM_TABLE,
|
|
5537
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5538
|
+
});
|
|
5539
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5540
|
+
const result = await this.#db.client.query(
|
|
5541
|
+
`UPDATE ${tableName} SET "isObserving" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`,
|
|
5542
|
+
[isObserving, nowStr, nowStr, id]
|
|
5543
|
+
);
|
|
5544
|
+
if (result.rowCount === 0) {
|
|
5545
|
+
throw new error.MastraError({
|
|
5546
|
+
id: storage.createStorageErrorId("PG", "SET_OBSERVING_FLAG", "NOT_FOUND"),
|
|
5547
|
+
text: `Observational memory record not found: ${id}`,
|
|
5548
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5549
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5550
|
+
details: { id, isObserving }
|
|
5551
|
+
});
|
|
5552
|
+
}
|
|
5553
|
+
} catch (error$1) {
|
|
5554
|
+
if (error$1 instanceof error.MastraError) {
|
|
5555
|
+
throw error$1;
|
|
5556
|
+
}
|
|
5557
|
+
throw new error.MastraError(
|
|
5558
|
+
{
|
|
5559
|
+
id: storage.createStorageErrorId("PG", "SET_OBSERVING_FLAG", "FAILED"),
|
|
5560
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5561
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5562
|
+
details: { id, isObserving }
|
|
5563
|
+
},
|
|
5564
|
+
error$1
|
|
5565
|
+
);
|
|
5566
|
+
}
|
|
5567
|
+
}
|
|
5568
|
+
async clearObservationalMemory(threadId, resourceId) {
|
|
5569
|
+
try {
|
|
5570
|
+
const lookupKey = this.getOMKey(threadId, resourceId);
|
|
5571
|
+
const tableName = getTableName3({
|
|
5572
|
+
indexName: OM_TABLE,
|
|
5573
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5574
|
+
});
|
|
5575
|
+
await this.#db.client.none(`DELETE FROM ${tableName} WHERE "lookupKey" = $1`, [lookupKey]);
|
|
5576
|
+
} catch (error$1) {
|
|
5577
|
+
throw new error.MastraError(
|
|
5578
|
+
{
|
|
5579
|
+
id: storage.createStorageErrorId("PG", "CLEAR_OBSERVATIONAL_MEMORY", "FAILED"),
|
|
5580
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5581
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5582
|
+
details: { threadId, resourceId }
|
|
5583
|
+
},
|
|
5584
|
+
error$1
|
|
5585
|
+
);
|
|
5586
|
+
}
|
|
5587
|
+
}
|
|
5588
|
+
async addPendingMessageTokens(id, tokenCount) {
|
|
5589
|
+
try {
|
|
5590
|
+
const tableName = getTableName3({
|
|
5591
|
+
indexName: OM_TABLE,
|
|
5592
|
+
schemaName: getSchemaName3(this.#schema)
|
|
5593
|
+
});
|
|
5594
|
+
const nowStr = (/* @__PURE__ */ new Date()).toISOString();
|
|
5595
|
+
const result = await this.#db.client.query(
|
|
5596
|
+
`UPDATE ${tableName} SET
|
|
5597
|
+
"pendingMessageTokens" = "pendingMessageTokens" + $1,
|
|
5598
|
+
"updatedAt" = $2,
|
|
5599
|
+
"updatedAtZ" = $3
|
|
5600
|
+
WHERE id = $4`,
|
|
5601
|
+
[tokenCount, nowStr, nowStr, id]
|
|
5602
|
+
);
|
|
5603
|
+
if (result.rowCount === 0) {
|
|
5604
|
+
throw new error.MastraError({
|
|
5605
|
+
id: storage.createStorageErrorId("PG", "ADD_PENDING_MESSAGE_TOKENS", "NOT_FOUND"),
|
|
5606
|
+
text: `Observational memory record not found: ${id}`,
|
|
5607
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5608
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5609
|
+
details: { id, tokenCount }
|
|
5610
|
+
});
|
|
5611
|
+
}
|
|
5612
|
+
} catch (error$1) {
|
|
5613
|
+
if (error$1 instanceof error.MastraError) {
|
|
5614
|
+
throw error$1;
|
|
5615
|
+
}
|
|
5616
|
+
throw new error.MastraError(
|
|
5617
|
+
{
|
|
5618
|
+
id: storage.createStorageErrorId("PG", "ADD_PENDING_MESSAGE_TOKENS", "FAILED"),
|
|
5619
|
+
domain: error.ErrorDomain.STORAGE,
|
|
5620
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
5621
|
+
details: { id, tokenCount }
|
|
5622
|
+
},
|
|
5623
|
+
error$1
|
|
5624
|
+
);
|
|
5625
|
+
}
|
|
5626
|
+
}
|
|
4864
5627
|
};
|
|
4865
5628
|
var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorage {
|
|
4866
5629
|
#db;
|