@mastra/pg 1.20.1-alpha.2 → 1.21.0-alpha.4
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 +24 -0
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-storage.md +1 -0
- package/dist/index.cjs +1014 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1015 -9
- package/dist/index.js.map +1 -1
- package/dist/storage/domains/knowledge/index.d.ts +84 -0
- package/dist/storage/domains/knowledge/index.d.ts.map +1 -0
- package/dist/storage/factory-storage.d.ts +22 -0
- package/dist/storage/factory-storage.d.ts.map +1 -1
- package/dist/storage/index.d.ts +2 -1
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -351,7 +351,7 @@ const FILTER_OPERATORS = {
|
|
|
351
351
|
return {
|
|
352
352
|
sql,
|
|
353
353
|
needsValue: true,
|
|
354
|
-
transformValue: () => Array.isArray(value) ? value.map(String) : typeof value === "string" ? escapeLikePattern(value) : value
|
|
354
|
+
transformValue: () => Array.isArray(value) ? value.map(String) : typeof value === "string" ? escapeLikePattern$1(value) : value
|
|
355
355
|
};
|
|
356
356
|
},
|
|
357
357
|
/**
|
|
@@ -375,7 +375,7 @@ const FILTER_OPERATORS = {
|
|
|
375
375
|
const parseJsonPathKey = (key) => {
|
|
376
376
|
return (key !== "" ? (0, _mastra_core_utils.parseFieldKey)(key) : "").replace(/\./g, ",");
|
|
377
377
|
};
|
|
378
|
-
function escapeLikePattern(str) {
|
|
378
|
+
function escapeLikePattern$1(str) {
|
|
379
379
|
return str.replace(/([%_\\])/g, "\\$1");
|
|
380
380
|
}
|
|
381
381
|
/**
|
|
@@ -4712,7 +4712,7 @@ function serializeJson(v) {
|
|
|
4712
4712
|
if (typeof v === "object" && v != null) return JSON.stringify(v);
|
|
4713
4713
|
return v ?? null;
|
|
4714
4714
|
}
|
|
4715
|
-
function parseJson$
|
|
4715
|
+
function parseJson$2(v) {
|
|
4716
4716
|
if (typeof v === "string") try {
|
|
4717
4717
|
return JSON.parse(v);
|
|
4718
4718
|
} catch {
|
|
@@ -4731,14 +4731,14 @@ function rowToTask(row) {
|
|
|
4731
4731
|
status: row.status,
|
|
4732
4732
|
toolName: row.tool_name,
|
|
4733
4733
|
toolCallId: row.tool_call_id,
|
|
4734
|
-
args: parseJson$
|
|
4734
|
+
args: parseJson$2(row.args),
|
|
4735
4735
|
agentId: row.agent_id,
|
|
4736
4736
|
threadId: row.thread_id ?? void 0,
|
|
4737
4737
|
resourceId: row.resource_id ?? void 0,
|
|
4738
4738
|
runId: row.run_id,
|
|
4739
|
-
result: parseJson$
|
|
4740
|
-
error: parseJson$
|
|
4741
|
-
suspendPayload: parseJson$
|
|
4739
|
+
result: parseJson$2(row.result),
|
|
4740
|
+
error: parseJson$2(row.error),
|
|
4741
|
+
suspendPayload: parseJson$2(row.suspend_payload),
|
|
4742
4742
|
retryCount: Number(row.retry_count),
|
|
4743
4743
|
maxRetries: Number(row.max_retries),
|
|
4744
4744
|
timeoutMs: Number(row.timeout_ms),
|
|
@@ -7608,6 +7608,977 @@ var FavoritesPG = class FavoritesPG extends _mastra_core_storage.FavoritesStorag
|
|
|
7608
7608
|
}
|
|
7609
7609
|
};
|
|
7610
7610
|
//#endregion
|
|
7611
|
+
//#region src/storage/domains/knowledge/index.ts
|
|
7612
|
+
const camelCaseColumns = [
|
|
7613
|
+
"canonicalName",
|
|
7614
|
+
"scopeKey",
|
|
7615
|
+
"mergedInto",
|
|
7616
|
+
"createdAt",
|
|
7617
|
+
"updatedAt",
|
|
7618
|
+
"node",
|
|
7619
|
+
"sourceThreadId",
|
|
7620
|
+
"capturedAt",
|
|
7621
|
+
"maxScope",
|
|
7622
|
+
"deletedAt",
|
|
7623
|
+
"deletedBy",
|
|
7624
|
+
"sourceType",
|
|
7625
|
+
"sourceId",
|
|
7626
|
+
"recordId",
|
|
7627
|
+
"lastKnowledgeId",
|
|
7628
|
+
"recordType",
|
|
7629
|
+
"idempotencyKey",
|
|
7630
|
+
"documentId",
|
|
7631
|
+
"documentType",
|
|
7632
|
+
"availableAt",
|
|
7633
|
+
"claimedAt",
|
|
7634
|
+
"claimedBy",
|
|
7635
|
+
"completedAt"
|
|
7636
|
+
];
|
|
7637
|
+
function transformSqlCode(sql, transform) {
|
|
7638
|
+
return sql.split(/('(?:''|[^'])*')/g).map((part, index) => index % 2 === 0 ? transform(part) : part).join("");
|
|
7639
|
+
}
|
|
7640
|
+
function postgresSql(sql, schemaName) {
|
|
7641
|
+
let normalized = transformSqlCode(sql, (code) => {
|
|
7642
|
+
let transformed = code.replace(/jsonb\(\?\)/g, "?::jsonb");
|
|
7643
|
+
for (const column of camelCaseColumns) transformed = transformed.replace(new RegExp(`(?<!")\\b${column}\\b(?!")`, "g"), `"${column}"`);
|
|
7644
|
+
return transformed;
|
|
7645
|
+
});
|
|
7646
|
+
if (schemaName) {
|
|
7647
|
+
const quotedSchema = `"${(0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name")}"`;
|
|
7648
|
+
normalized = transformSqlCode(normalized, (code) => {
|
|
7649
|
+
let transformed = code;
|
|
7650
|
+
for (const table of [
|
|
7651
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_NODES,
|
|
7652
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
|
|
7653
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
|
|
7654
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS,
|
|
7655
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
|
|
7656
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX
|
|
7657
|
+
]) transformed = transformed.replaceAll(`"${table}"`, `${quotedSchema}."${table}"`);
|
|
7658
|
+
return transformed;
|
|
7659
|
+
});
|
|
7660
|
+
}
|
|
7661
|
+
let index = 0;
|
|
7662
|
+
return transformSqlCode(normalized, (code) => code.replace(/\?/g, () => `$${++index}`));
|
|
7663
|
+
}
|
|
7664
|
+
function createExecutor(client, schemaName) {
|
|
7665
|
+
return { async execute(statement) {
|
|
7666
|
+
const sql = typeof statement === "string" ? statement : statement.sql;
|
|
7667
|
+
const args = typeof statement === "string" ? [] : statement.args ?? [];
|
|
7668
|
+
const result = await client.query(postgresSql(sql, schemaName), args);
|
|
7669
|
+
return {
|
|
7670
|
+
rows: result.rows,
|
|
7671
|
+
rowsAffected: result.rowCount ?? 0
|
|
7672
|
+
};
|
|
7673
|
+
} };
|
|
7674
|
+
}
|
|
7675
|
+
const visibleSql = `(scopeKey = ? OR LEFT(?, LENGTH(scopeKey) + 1) = scopeKey || chr(31))`;
|
|
7676
|
+
function parseJson$1(value) {
|
|
7677
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
7678
|
+
if (value instanceof Uint8Array) return JSON.parse(new TextDecoder().decode(value));
|
|
7679
|
+
if (value instanceof ArrayBuffer) return JSON.parse(new TextDecoder().decode(value));
|
|
7680
|
+
return value;
|
|
7681
|
+
}
|
|
7682
|
+
/**
|
|
7683
|
+
* Knowledge timestamps are written as UTC digits into timezone-naive columns
|
|
7684
|
+
* ({@link postgresTimestamp} and the ISO strings passed to inserts), but the
|
|
7685
|
+
* driver parses naive columns in the process-local timezone. Reinterpret the
|
|
7686
|
+
* parsed components as UTC so reads return the digits that were stored.
|
|
7687
|
+
*/
|
|
7688
|
+
function toDate$1(value) {
|
|
7689
|
+
if (value instanceof Date) return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate(), value.getHours(), value.getMinutes(), value.getSeconds(), value.getMilliseconds()));
|
|
7690
|
+
const text = String(value);
|
|
7691
|
+
if (/(Z|[+-]\d{2}(:?\d{2})?)$/.test(text)) return new Date(text);
|
|
7692
|
+
return /* @__PURE__ */ new Date(`${text.replace(" ", "T")}Z`);
|
|
7693
|
+
}
|
|
7694
|
+
function optionalDate(value) {
|
|
7695
|
+
return value == null ? void 0 : toDate$1(value);
|
|
7696
|
+
}
|
|
7697
|
+
function postgresTimestamp(value) {
|
|
7698
|
+
const pad = (part, width = 2) => String(part).padStart(width, "0");
|
|
7699
|
+
return `${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}.${pad(value.getUTCMilliseconds(), 3)}`;
|
|
7700
|
+
}
|
|
7701
|
+
function canonicalName(name) {
|
|
7702
|
+
return name.trim().toLocaleLowerCase();
|
|
7703
|
+
}
|
|
7704
|
+
function nodeReferenceId(node) {
|
|
7705
|
+
return typeof node === "string" ? node : node.id;
|
|
7706
|
+
}
|
|
7707
|
+
function escapeLikePattern(value) {
|
|
7708
|
+
return value.replaceAll("=", "==").replaceAll("%", "=%").replaceAll("_", "=_");
|
|
7709
|
+
}
|
|
7710
|
+
function parseNode(row) {
|
|
7711
|
+
return {
|
|
7712
|
+
id: String(row.id),
|
|
7713
|
+
type: "node",
|
|
7714
|
+
name: String(row.name),
|
|
7715
|
+
kind: String(row.kind),
|
|
7716
|
+
content: row.content == null ? void 0 : String(row.content),
|
|
7717
|
+
scope: parseJson$1(row.scopeJson ?? row.scope),
|
|
7718
|
+
version: Number(row.version),
|
|
7719
|
+
mergedInto: row.mergedInto == null ? void 0 : String(row.mergedInto),
|
|
7720
|
+
createdAt: toDate$1(row.createdAt),
|
|
7721
|
+
updatedAt: toDate$1(row.updatedAt)
|
|
7722
|
+
};
|
|
7723
|
+
}
|
|
7724
|
+
function parseKnowledge(row) {
|
|
7725
|
+
return {
|
|
7726
|
+
id: String(row.id),
|
|
7727
|
+
node: String(row.node),
|
|
7728
|
+
text: String(row.text),
|
|
7729
|
+
scope: parseJson$1(row.scopeJson ?? row.scope),
|
|
7730
|
+
sourceThreadId: String(row.sourceThreadId),
|
|
7731
|
+
capturedAt: toDate$1(row.capturedAt),
|
|
7732
|
+
when: optionalDate(row.when),
|
|
7733
|
+
maxScope: row.maxScope == null ? void 0 : String(row.maxScope),
|
|
7734
|
+
metadata: row.metadata == null ? void 0 : parseJson$1(row.metadata),
|
|
7735
|
+
deletedAt: optionalDate(row.deletedAt),
|
|
7736
|
+
deletedBy: row.deletedBy == null ? void 0 : String(row.deletedBy)
|
|
7737
|
+
};
|
|
7738
|
+
}
|
|
7739
|
+
function parseOutbox(row) {
|
|
7740
|
+
return {
|
|
7741
|
+
id: String(row.id),
|
|
7742
|
+
idempotencyKey: String(row.idempotencyKey),
|
|
7743
|
+
documentId: String(row.documentId),
|
|
7744
|
+
documentType: String(row.documentType),
|
|
7745
|
+
operation: String(row.operation),
|
|
7746
|
+
scope: parseJson$1(row.scopeJson ?? row.scope),
|
|
7747
|
+
status: String(row.status),
|
|
7748
|
+
attempts: Number(row.attempts),
|
|
7749
|
+
availableAt: toDate$1(row.availableAt),
|
|
7750
|
+
claimedAt: optionalDate(row.claimedAt),
|
|
7751
|
+
claimedBy: row.claimedBy == null ? void 0 : String(row.claimedBy),
|
|
7752
|
+
createdAt: toDate$1(row.createdAt),
|
|
7753
|
+
completedAt: optionalDate(row.completedAt)
|
|
7754
|
+
};
|
|
7755
|
+
}
|
|
7756
|
+
function knowledgeIndexes(schemaName) {
|
|
7757
|
+
const table = (name) => {
|
|
7758
|
+
const quotedName = `"${(0, _mastra_core_utils.parseSqlIdentifier)(name, "table name")}"`;
|
|
7759
|
+
return schemaName ? `"${(0, _mastra_core_utils.parseSqlIdentifier)(schemaName, "schema name")}".${quotedName}` : quotedName;
|
|
7760
|
+
};
|
|
7761
|
+
return [
|
|
7762
|
+
{
|
|
7763
|
+
name: "idx_knowledge_nodes_identity",
|
|
7764
|
+
sql: `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_nodes_identity ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_NODES)} ("type", "scopeKey", "canonicalName");`
|
|
7765
|
+
},
|
|
7766
|
+
{
|
|
7767
|
+
name: "idx_knowledge_nodes_scope",
|
|
7768
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_scope ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_NODES)} ("scopeKey", "type");`
|
|
7769
|
+
},
|
|
7770
|
+
{
|
|
7771
|
+
name: "idx_knowledge_records_node_latest",
|
|
7772
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_records_node_latest ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS)} ("node", "id" DESC);`
|
|
7773
|
+
},
|
|
7774
|
+
{
|
|
7775
|
+
name: "idx_knowledge_records_thread_latest",
|
|
7776
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_records_thread_latest ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS)} ("sourceThreadId", "id" DESC);`
|
|
7777
|
+
},
|
|
7778
|
+
{
|
|
7779
|
+
name: "idx_knowledge_mentions_record",
|
|
7780
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_mentions_record ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS)} ("recordId", "sourceType", "sourceId");`
|
|
7781
|
+
},
|
|
7782
|
+
{
|
|
7783
|
+
name: "idx_knowledge_activity_latest",
|
|
7784
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_latest ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY)} ("id" DESC);`
|
|
7785
|
+
},
|
|
7786
|
+
{
|
|
7787
|
+
name: "idx_knowledge_outbox_idempotency",
|
|
7788
|
+
sql: `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_outbox_idempotency ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX)} ("idempotencyKey");`
|
|
7789
|
+
},
|
|
7790
|
+
{
|
|
7791
|
+
name: "idx_knowledge_outbox_claim",
|
|
7792
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_outbox_claim ON ${table(_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX)} ("status", "availableAt", "createdAt");`
|
|
7793
|
+
}
|
|
7794
|
+
];
|
|
7795
|
+
}
|
|
7796
|
+
function knowledgeIndexDDL(schemaName) {
|
|
7797
|
+
return knowledgeIndexes(schemaName).map((index) => index.sql);
|
|
7798
|
+
}
|
|
7799
|
+
var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
|
|
7800
|
+
static MANAGED_TABLES = [
|
|
7801
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_NODES,
|
|
7802
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
|
|
7803
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
|
|
7804
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS,
|
|
7805
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
|
|
7806
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX
|
|
7807
|
+
];
|
|
7808
|
+
static getExportDDL(schemaName) {
|
|
7809
|
+
return [
|
|
7810
|
+
generateTableSQL({
|
|
7811
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_NODES,
|
|
7812
|
+
schema: _mastra_core_storage.KNOWLEDGE_NODES_SCHEMA,
|
|
7813
|
+
schemaName,
|
|
7814
|
+
includeAllConstraints: true
|
|
7815
|
+
}),
|
|
7816
|
+
generateTableSQL({
|
|
7817
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
|
|
7818
|
+
schema: _mastra_core_storage.KNOWLEDGE_RECORDS_SCHEMA,
|
|
7819
|
+
schemaName,
|
|
7820
|
+
includeAllConstraints: true
|
|
7821
|
+
}),
|
|
7822
|
+
generateTableSQL({
|
|
7823
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
|
|
7824
|
+
schema: _mastra_core_storage.KNOWLEDGE_MENTIONS_SCHEMA,
|
|
7825
|
+
schemaName,
|
|
7826
|
+
compositePrimaryKey: [
|
|
7827
|
+
"sourceType",
|
|
7828
|
+
"sourceId",
|
|
7829
|
+
"recordId"
|
|
7830
|
+
],
|
|
7831
|
+
includeAllConstraints: true
|
|
7832
|
+
}),
|
|
7833
|
+
generateTableSQL({
|
|
7834
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_CURSORS,
|
|
7835
|
+
schema: _mastra_core_storage.KNOWLEDGE_CURSORS_SCHEMA,
|
|
7836
|
+
schemaName,
|
|
7837
|
+
compositePrimaryKey: ["sourceThreadId", "agent"],
|
|
7838
|
+
includeAllConstraints: true
|
|
7839
|
+
}),
|
|
7840
|
+
generateTableSQL({
|
|
7841
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
|
|
7842
|
+
schema: _mastra_core_storage.KNOWLEDGE_ACTIVITY_SCHEMA,
|
|
7843
|
+
schemaName,
|
|
7844
|
+
includeAllConstraints: true
|
|
7845
|
+
}),
|
|
7846
|
+
generateTableSQL({
|
|
7847
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
|
|
7848
|
+
schema: _mastra_core_storage.KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA,
|
|
7849
|
+
schemaName,
|
|
7850
|
+
includeAllConstraints: true
|
|
7851
|
+
}),
|
|
7852
|
+
...knowledgeIndexDDL(schemaName)
|
|
7853
|
+
];
|
|
7854
|
+
}
|
|
7855
|
+
#client;
|
|
7856
|
+
#executor;
|
|
7857
|
+
#db;
|
|
7858
|
+
#schemaName;
|
|
7859
|
+
constructor(config) {
|
|
7860
|
+
super();
|
|
7861
|
+
const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
|
|
7862
|
+
this.#client = client;
|
|
7863
|
+
this.#schemaName = schemaName;
|
|
7864
|
+
this.#executor = createExecutor(client, schemaName);
|
|
7865
|
+
this.#db = new PgDB({
|
|
7866
|
+
client,
|
|
7867
|
+
schemaName,
|
|
7868
|
+
skipDefaultIndexes
|
|
7869
|
+
});
|
|
7870
|
+
}
|
|
7871
|
+
async init() {
|
|
7872
|
+
await this.#db.createTable({
|
|
7873
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_NODES,
|
|
7874
|
+
schema: _mastra_core_storage.KNOWLEDGE_NODES_SCHEMA
|
|
7875
|
+
});
|
|
7876
|
+
await this.#db.createTable({
|
|
7877
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
|
|
7878
|
+
schema: _mastra_core_storage.KNOWLEDGE_RECORDS_SCHEMA
|
|
7879
|
+
});
|
|
7880
|
+
await this.#db.createTable({
|
|
7881
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
|
|
7882
|
+
schema: _mastra_core_storage.KNOWLEDGE_MENTIONS_SCHEMA,
|
|
7883
|
+
compositePrimaryKey: [
|
|
7884
|
+
"sourceType",
|
|
7885
|
+
"sourceId",
|
|
7886
|
+
"recordId"
|
|
7887
|
+
]
|
|
7888
|
+
});
|
|
7889
|
+
await this.#db.createTable({
|
|
7890
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_CURSORS,
|
|
7891
|
+
schema: _mastra_core_storage.KNOWLEDGE_CURSORS_SCHEMA,
|
|
7892
|
+
compositePrimaryKey: ["sourceThreadId", "agent"]
|
|
7893
|
+
});
|
|
7894
|
+
await this.#db.createTable({
|
|
7895
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
|
|
7896
|
+
schema: _mastra_core_storage.KNOWLEDGE_ACTIVITY_SCHEMA
|
|
7897
|
+
});
|
|
7898
|
+
await this.#db.createTable({
|
|
7899
|
+
tableName: _mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
|
|
7900
|
+
schema: _mastra_core_storage.KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA
|
|
7901
|
+
});
|
|
7902
|
+
await Promise.all(knowledgeIndexes(this.#schemaName).map((index) => this.#db.createIndexFromStatement(index.name, index.sql)));
|
|
7903
|
+
}
|
|
7904
|
+
async dangerouslyClearAll() {
|
|
7905
|
+
await this.#transaction(async (tx) => {
|
|
7906
|
+
for (const table of [
|
|
7907
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
|
|
7908
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
|
|
7909
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_NODES,
|
|
7910
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS,
|
|
7911
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
|
|
7912
|
+
_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX
|
|
7913
|
+
]) await tx.execute(`DELETE FROM "${table}"`);
|
|
7914
|
+
});
|
|
7915
|
+
}
|
|
7916
|
+
async createNode(input) {
|
|
7917
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
|
|
7918
|
+
return this.#transaction(async (tx) => {
|
|
7919
|
+
const existing = await this.#getNodeByName(tx, input.name, scope);
|
|
7920
|
+
if (existing) {
|
|
7921
|
+
const terminal = await this.#resolveTerminalNode(tx, existing.id);
|
|
7922
|
+
if (!(0, _mastra_core_storage.isKnowledgeScopeVisible)(terminal.scope, scope)) throw new Error(`Merged knowledge node is not visible from scope: ${input.name}`);
|
|
7923
|
+
return terminal;
|
|
7924
|
+
}
|
|
7925
|
+
const now = /* @__PURE__ */ new Date();
|
|
7926
|
+
const node = {
|
|
7927
|
+
id: input.id ?? crypto.randomUUID(),
|
|
7928
|
+
type: "node",
|
|
7929
|
+
name: input.name.trim(),
|
|
7930
|
+
kind: input.kind,
|
|
7931
|
+
content: input.content,
|
|
7932
|
+
scope,
|
|
7933
|
+
version: 1,
|
|
7934
|
+
createdAt: now,
|
|
7935
|
+
updatedAt: now
|
|
7936
|
+
};
|
|
7937
|
+
await tx.execute({
|
|
7938
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,?,jsonb(?),?,?,NULL,?,?)`,
|
|
7939
|
+
args: [
|
|
7940
|
+
node.id,
|
|
7941
|
+
"node",
|
|
7942
|
+
node.name,
|
|
7943
|
+
canonicalName(node.name),
|
|
7944
|
+
node.kind,
|
|
7945
|
+
node.content ?? null,
|
|
7946
|
+
JSON.stringify(scope),
|
|
7947
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
7948
|
+
node.version,
|
|
7949
|
+
now.toISOString(),
|
|
7950
|
+
now.toISOString()
|
|
7951
|
+
]
|
|
7952
|
+
});
|
|
7953
|
+
await this.#replaceMentions(tx, "node", node.id, node.content ?? "", input.resolutionScope ?? scope, scope);
|
|
7954
|
+
await this.#activity(tx, "node-created", "node", node.id, scope);
|
|
7955
|
+
await this.#outbox(tx, "node", node.id, "upsert", node.version, scope);
|
|
7956
|
+
return node;
|
|
7957
|
+
});
|
|
7958
|
+
}
|
|
7959
|
+
async getNode(id) {
|
|
7960
|
+
return this.#getNode(this.#executor, id);
|
|
7961
|
+
}
|
|
7962
|
+
async getNodeByName(input) {
|
|
7963
|
+
return this.#getNodeByName(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
7964
|
+
}
|
|
7965
|
+
async resolveNode(input) {
|
|
7966
|
+
return this.#resolveNode(this.#executor, input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
7967
|
+
}
|
|
7968
|
+
async listNodes(input) {
|
|
7969
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
7970
|
+
const clauses = [
|
|
7971
|
+
`type = 'node'`,
|
|
7972
|
+
"mergedInto IS NULL",
|
|
7973
|
+
visibleSql
|
|
7974
|
+
];
|
|
7975
|
+
const args = [key, key];
|
|
7976
|
+
if (input.namePrefix) {
|
|
7977
|
+
clauses.push("canonicalName LIKE ? ESCAPE '='");
|
|
7978
|
+
args.push(`${escapeLikePattern(canonicalName(input.namePrefix))}%`);
|
|
7979
|
+
}
|
|
7980
|
+
if (input.kind) {
|
|
7981
|
+
clauses.push("kind = ?");
|
|
7982
|
+
args.push(input.kind);
|
|
7983
|
+
}
|
|
7984
|
+
if (input.hasContent !== void 0) clauses.push(input.hasContent ? "content IS NOT NULL AND content <> ''" : "(content IS NULL OR content = '')");
|
|
7985
|
+
if (input.cursor) {
|
|
7986
|
+
const cursor = (0, _mastra_core_storage.parseKnowledgeNodeCursor)(input.cursor, {
|
|
7987
|
+
namePrefix: input.namePrefix,
|
|
7988
|
+
kind: input.kind,
|
|
7989
|
+
hasContent: input.hasContent
|
|
7990
|
+
});
|
|
7991
|
+
const updatedAt = postgresTimestamp(cursor.updatedAt);
|
|
7992
|
+
clauses.push("(updatedAt < ? OR (updatedAt = ? AND (name > ? OR (name = ? AND id > ?))))");
|
|
7993
|
+
args.push(updatedAt, updatedAt, cursor.name, cursor.name, cursor.id);
|
|
7994
|
+
}
|
|
7995
|
+
args.push(input.limit ?? 100);
|
|
7996
|
+
return (await this.#executor.execute({
|
|
7997
|
+
sql: `SELECT *, scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE ${clauses.join(" AND ")} ORDER BY updatedAt DESC, name ASC, id ASC LIMIT ?`,
|
|
7998
|
+
args
|
|
7999
|
+
})).rows.map(parseNode);
|
|
8000
|
+
}
|
|
8001
|
+
async updateNode(input) {
|
|
8002
|
+
return this.#transaction(async (tx) => {
|
|
8003
|
+
const existing = await this.#getNode(tx, input.id);
|
|
8004
|
+
if (!existing) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.id);
|
|
8005
|
+
if (existing.mergedInto) throw new Error(`Cannot update merged knowledge node: ${input.id}`);
|
|
8006
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope ?? existing.scope);
|
|
8007
|
+
const name = (input.name ?? existing.name).trim();
|
|
8008
|
+
const content = input.content ?? existing.content;
|
|
8009
|
+
const now = /* @__PURE__ */ new Date();
|
|
8010
|
+
if ((await tx.execute({
|
|
8011
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" SET name=?,canonicalName=?,kind=?,content=?,scope=jsonb(?),scopeKey=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=?`,
|
|
8012
|
+
args: [
|
|
8013
|
+
name,
|
|
8014
|
+
canonicalName(name),
|
|
8015
|
+
input.kind ?? existing.kind,
|
|
8016
|
+
content ?? null,
|
|
8017
|
+
JSON.stringify(scope),
|
|
8018
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
8019
|
+
now.toISOString(),
|
|
8020
|
+
input.id,
|
|
8021
|
+
input.version
|
|
8022
|
+
]
|
|
8023
|
+
})).rowsAffected === 0) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
|
|
8024
|
+
if (input.content !== void 0 || input.name !== void 0 || input.scope !== void 0) await this.#replaceMentions(tx, "node", input.id, content ?? "", input.resolutionScope ?? scope, scope);
|
|
8025
|
+
await this.#activity(tx, "node-updated", "node", input.id, scope);
|
|
8026
|
+
if ((0, _mastra_core_storage.knowledgeScopeKey)(existing.scope) !== (0, _mastra_core_storage.knowledgeScopeKey)(scope)) {
|
|
8027
|
+
await this.#outbox(tx, "node", input.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), existing.scope);
|
|
8028
|
+
const records = await tx.execute({
|
|
8029
|
+
sql: `SELECT id,scope AS "scopeJson",deletedAt FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
|
|
8030
|
+
args: [input.id]
|
|
8031
|
+
});
|
|
8032
|
+
for (const row of records.rows) {
|
|
8033
|
+
const factScope = parseJson$1(row.scopeJson);
|
|
8034
|
+
await this.#outbox(tx, "record", String(row.id), "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), factScope);
|
|
8035
|
+
if (row.deletedAt == null) await this.#outbox(tx, "record", String(row.id), "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), factScope);
|
|
8036
|
+
}
|
|
8037
|
+
}
|
|
8038
|
+
await this.#outbox(tx, "node", input.id, "upsert", input.version + 1, scope);
|
|
8039
|
+
return {
|
|
8040
|
+
...existing,
|
|
8041
|
+
name,
|
|
8042
|
+
kind: input.kind ?? existing.kind,
|
|
8043
|
+
content,
|
|
8044
|
+
scope,
|
|
8045
|
+
version: input.version + 1,
|
|
8046
|
+
updatedAt: now
|
|
8047
|
+
};
|
|
8048
|
+
});
|
|
8049
|
+
}
|
|
8050
|
+
async mergeNodes(input) {
|
|
8051
|
+
if (input.sourceId === input.targetId) throw new Error("Cannot merge a knowledge node into itself");
|
|
8052
|
+
return this.#transaction(async (tx) => {
|
|
8053
|
+
const source = await this.#getNode(tx, input.sourceId);
|
|
8054
|
+
if (!source) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.sourceId);
|
|
8055
|
+
const target = await this.#resolveTerminalNode(tx, input.targetId);
|
|
8056
|
+
if (!target) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.targetId);
|
|
8057
|
+
if (target.id === source.id) throw new Error("Cannot create a knowledge merge cycle");
|
|
8058
|
+
if (!(0, _mastra_core_storage.isKnowledgeScopeVisible)(target.scope, source.scope)) throw new Error("Cannot merge a knowledge node into a target that is narrower than its source scope");
|
|
8059
|
+
const affected = await tx.execute({
|
|
8060
|
+
sql: `SELECT DISTINCT m.sourceType,m.sourceId,COALESCE(f.scope,r.scope) AS "scopeJson",CASE WHEN f.deletedAt IS NULL THEN 0 ELSE 1 END AS deleted FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" m LEFT JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" f ON m.sourceType='record' AND f.id=m.sourceId LEFT JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" r ON m.sourceType='node' AND r.id=m.sourceId WHERE m.recordId=?`,
|
|
8061
|
+
args: [source.id]
|
|
8062
|
+
});
|
|
8063
|
+
const movedFacts = await tx.execute({
|
|
8064
|
+
sql: `SELECT id,scope AS "scopeJson",deletedAt FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
|
|
8065
|
+
args: [source.id]
|
|
8066
|
+
});
|
|
8067
|
+
if ((await tx.execute({
|
|
8068
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" SET mergedInto=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=? AND mergedInto IS NULL`,
|
|
8069
|
+
args: [
|
|
8070
|
+
target.id,
|
|
8071
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
8072
|
+
source.id,
|
|
8073
|
+
input.sourceVersion
|
|
8074
|
+
]
|
|
8075
|
+
})).rowsAffected === 0) throw new _mastra_core_storage.KnowledgeConflictError(source.id);
|
|
8076
|
+
await tx.execute({
|
|
8077
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" SET node=? WHERE node=?`,
|
|
8078
|
+
args: [target.id, source.id]
|
|
8079
|
+
});
|
|
8080
|
+
await tx.execute({
|
|
8081
|
+
sql: `DELETE FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" WHERE recordId=? AND EXISTS (SELECT 1 FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" target WHERE target.sourceType="${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}".sourceType AND target.sourceId="${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}".sourceId AND target.recordId=?)`,
|
|
8082
|
+
args: [source.id, target.id]
|
|
8083
|
+
});
|
|
8084
|
+
await tx.execute({
|
|
8085
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" SET recordId=? WHERE recordId=?`,
|
|
8086
|
+
args: [target.id, source.id]
|
|
8087
|
+
});
|
|
8088
|
+
for (const row of movedFacts.rows) await this.#outbox(tx, "record", String(row.id), row.deletedAt == null ? "upsert" : "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), parseJson$1(row.scopeJson));
|
|
8089
|
+
for (const row of affected.rows) await this.#outbox(tx, String(row.sourceType), String(row.sourceId), Number(row.deleted) ? "delete" : "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), parseJson$1(row.scopeJson));
|
|
8090
|
+
await this.#activity(tx, "node-merged", "node", source.id, source.scope);
|
|
8091
|
+
await this.#outbox(tx, "node", source.id, "delete", input.sourceVersion + 1, source.scope);
|
|
8092
|
+
await this.#outbox(tx, "node", target.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), target.scope);
|
|
8093
|
+
return target;
|
|
8094
|
+
});
|
|
8095
|
+
}
|
|
8096
|
+
async appendKnowledge(input) {
|
|
8097
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
|
|
8098
|
+
const resolutionScope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.resolutionScope);
|
|
8099
|
+
const defaultScope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.defaultScope);
|
|
8100
|
+
(0, _mastra_core_storage.assertKnowledgeScopeWithinCeiling)(scope, input.maxScope);
|
|
8101
|
+
return this.#transaction(async (tx) => {
|
|
8102
|
+
const parent = await this.#resolveTerminalNode(tx, nodeReferenceId(input.node));
|
|
8103
|
+
if (!parent) throw new _mastra_core_storage.KnowledgeNotFoundError("node", nodeReferenceId(input.node));
|
|
8104
|
+
const record = {
|
|
8105
|
+
id: input.id ?? (0, _mastra_core_storage.createKnowledgeUlid)(),
|
|
8106
|
+
node: parent.id,
|
|
8107
|
+
text: input.text,
|
|
8108
|
+
scope,
|
|
8109
|
+
sourceThreadId: input.sourceThreadId,
|
|
8110
|
+
capturedAt: /* @__PURE__ */ new Date(),
|
|
8111
|
+
when: input.when ? new Date(input.when) : void 0,
|
|
8112
|
+
maxScope: input.maxScope,
|
|
8113
|
+
metadata: input.metadata
|
|
8114
|
+
};
|
|
8115
|
+
await tx.execute({
|
|
8116
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" (id,node,text,scope,scopeKey,sourceThreadId,capturedAt,"when",maxScope,metadata,deletedAt,deletedBy) VALUES (?,?,?,jsonb(?),?,?,?,?,?,jsonb(?),NULL,NULL)`,
|
|
8117
|
+
args: [
|
|
8118
|
+
record.id,
|
|
8119
|
+
record.node,
|
|
8120
|
+
record.text,
|
|
8121
|
+
JSON.stringify(scope),
|
|
8122
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
8123
|
+
record.sourceThreadId,
|
|
8124
|
+
record.capturedAt.toISOString(),
|
|
8125
|
+
record.when?.toISOString() ?? null,
|
|
8126
|
+
record.maxScope ?? null,
|
|
8127
|
+
record.metadata ? JSON.stringify(record.metadata) : null
|
|
8128
|
+
]
|
|
8129
|
+
});
|
|
8130
|
+
await this.#replaceMentions(tx, "record", record.id, record.text, resolutionScope, defaultScope);
|
|
8131
|
+
await this.#activity(tx, "record-created", "record", record.id, scope, record.sourceThreadId);
|
|
8132
|
+
await this.#outbox(tx, "record", record.id, "upsert", record.id, scope);
|
|
8133
|
+
return record;
|
|
8134
|
+
});
|
|
8135
|
+
}
|
|
8136
|
+
async getKnowledge(input) {
|
|
8137
|
+
const result = await this.#executor.execute({
|
|
8138
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${input.includeDeleted ? "" : " AND deletedAt IS NULL"}`,
|
|
8139
|
+
args: [input.id]
|
|
8140
|
+
});
|
|
8141
|
+
return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
|
|
8142
|
+
}
|
|
8143
|
+
async listKnowledgeAbout(input) {
|
|
8144
|
+
return this.#queryKnowledge(input, "about");
|
|
8145
|
+
}
|
|
8146
|
+
async listKnowledgeMentioning(input) {
|
|
8147
|
+
return this.#queryKnowledge(input, "mentioning");
|
|
8148
|
+
}
|
|
8149
|
+
async listKnowledgeRelatedTo(input) {
|
|
8150
|
+
return this.#queryKnowledge(input, "related");
|
|
8151
|
+
}
|
|
8152
|
+
async knowledgeBySource(input) {
|
|
8153
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
8154
|
+
const args = [
|
|
8155
|
+
input.sourceThreadId,
|
|
8156
|
+
key,
|
|
8157
|
+
key
|
|
8158
|
+
];
|
|
8159
|
+
if (input.after) args.push(input.after);
|
|
8160
|
+
const limit = input.limit ?? 100;
|
|
8161
|
+
args.push(limit + 1);
|
|
8162
|
+
const records = (await this.#executor.execute({
|
|
8163
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE sourceThreadId=? AND ${visibleSql}${input.includeDeleted ? "" : " AND deletedAt IS NULL"}${input.after ? " AND id > ?" : ""} ORDER BY id ASC LIMIT ?`,
|
|
8164
|
+
args
|
|
8165
|
+
})).rows.map(parseKnowledge);
|
|
8166
|
+
return {
|
|
8167
|
+
records: records.slice(0, limit),
|
|
8168
|
+
nextCursor: records.length > limit ? records[limit - 1]?.id : void 0
|
|
8169
|
+
};
|
|
8170
|
+
}
|
|
8171
|
+
async removeKnowledge(input) {
|
|
8172
|
+
return this.#transaction(async (tx) => {
|
|
8173
|
+
const record = await this.#getKnowledge(tx, input.id, true);
|
|
8174
|
+
if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
|
|
8175
|
+
if (record.deletedAt) return record;
|
|
8176
|
+
const deletedAt = /* @__PURE__ */ new Date();
|
|
8177
|
+
await tx.execute({
|
|
8178
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=?,deletedBy=? WHERE id=? AND deletedAt IS NULL`,
|
|
8179
|
+
args: [
|
|
8180
|
+
deletedAt.toISOString(),
|
|
8181
|
+
input.deletedBy,
|
|
8182
|
+
input.id
|
|
8183
|
+
]
|
|
8184
|
+
});
|
|
8185
|
+
await this.#activity(tx, "record-deleted", "record", input.id, record.scope, record.sourceThreadId);
|
|
8186
|
+
await this.#outbox(tx, "record", input.id, "delete", deletedAt.toISOString(), record.scope);
|
|
8187
|
+
return {
|
|
8188
|
+
...record,
|
|
8189
|
+
deletedAt,
|
|
8190
|
+
deletedBy: input.deletedBy
|
|
8191
|
+
};
|
|
8192
|
+
});
|
|
8193
|
+
}
|
|
8194
|
+
async restoreKnowledge(input) {
|
|
8195
|
+
return this.#transaction(async (tx) => {
|
|
8196
|
+
const record = await this.#getKnowledge(tx, input.id, true);
|
|
8197
|
+
if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
|
|
8198
|
+
if (!record.deletedAt) return record;
|
|
8199
|
+
await tx.execute({
|
|
8200
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=NULL,deletedBy=NULL WHERE id=?`,
|
|
8201
|
+
args: [input.id]
|
|
8202
|
+
});
|
|
8203
|
+
await this.#activity(tx, "record-restored", "record", input.id, record.scope, record.sourceThreadId);
|
|
8204
|
+
await this.#outbox(tx, "record", input.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope);
|
|
8205
|
+
return {
|
|
8206
|
+
...record,
|
|
8207
|
+
deletedAt: void 0,
|
|
8208
|
+
deletedBy: void 0
|
|
8209
|
+
};
|
|
8210
|
+
});
|
|
8211
|
+
}
|
|
8212
|
+
async rescopeKnowledge(input) {
|
|
8213
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
|
|
8214
|
+
return this.#transaction(async (tx) => {
|
|
8215
|
+
const record = await this.#getKnowledge(tx, input.id, true);
|
|
8216
|
+
if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
|
|
8217
|
+
(0, _mastra_core_storage.assertKnowledgeScopeWithinCeiling)(scope, record.maxScope);
|
|
8218
|
+
await tx.execute({
|
|
8219
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" SET scope=jsonb(?),scopeKey=? WHERE id=?`,
|
|
8220
|
+
args: [
|
|
8221
|
+
JSON.stringify(scope),
|
|
8222
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
8223
|
+
input.id
|
|
8224
|
+
]
|
|
8225
|
+
});
|
|
8226
|
+
await this.#activity(tx, "record-rescoped", "record", input.id, scope, record.sourceThreadId);
|
|
8227
|
+
if ((0, _mastra_core_storage.knowledgeScopeKey)(record.scope) !== (0, _mastra_core_storage.knowledgeScopeKey)(scope)) await this.#outbox(tx, "record", input.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope);
|
|
8228
|
+
if (!record.deletedAt) await this.#outbox(tx, "record", input.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), scope);
|
|
8229
|
+
return {
|
|
8230
|
+
...record,
|
|
8231
|
+
scope
|
|
8232
|
+
};
|
|
8233
|
+
});
|
|
8234
|
+
}
|
|
8235
|
+
async raiseKnowledgeCeiling(input) {
|
|
8236
|
+
return this.#transaction(async (tx) => {
|
|
8237
|
+
const record = await this.#getKnowledge(tx, input.id, true);
|
|
8238
|
+
if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
|
|
8239
|
+
(0, _mastra_core_storage.assertKnowledgeScopeWithinCeiling)(record.scope, input.maxScope);
|
|
8240
|
+
(0, _mastra_core_storage.assertKnowledgeCeilingRaised)(record.maxScope, input.maxScope);
|
|
8241
|
+
await tx.execute({
|
|
8242
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" SET maxScope=? WHERE id=?`,
|
|
8243
|
+
args: [input.maxScope ?? null, input.id]
|
|
8244
|
+
});
|
|
8245
|
+
return {
|
|
8246
|
+
...record,
|
|
8247
|
+
maxScope: input.maxScope
|
|
8248
|
+
};
|
|
8249
|
+
});
|
|
8250
|
+
}
|
|
8251
|
+
async search(input) {
|
|
8252
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
|
|
8253
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)(scope);
|
|
8254
|
+
const normalizedQuery = input.query.trim().toLocaleLowerCase();
|
|
8255
|
+
if (!normalizedQuery) return [];
|
|
8256
|
+
const query = `%${escapeLikePattern(normalizedQuery)}%`;
|
|
8257
|
+
const results = (await this.#executor.execute({
|
|
8258
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE mergedInto IS NULL AND ${visibleSql} AND (canonicalName LIKE ? ESCAPE '=' OR lower(COALESCE(kind,'')) LIKE ? ESCAPE '=' OR lower(COALESCE(content,'')) LIKE ? ESCAPE '=') ORDER BY updatedAt DESC LIMIT ?`,
|
|
8259
|
+
args: [
|
|
8260
|
+
key,
|
|
8261
|
+
key,
|
|
8262
|
+
query,
|
|
8263
|
+
query,
|
|
8264
|
+
query,
|
|
8265
|
+
input.limit ?? 20
|
|
8266
|
+
]
|
|
8267
|
+
})).rows.map((row) => ({
|
|
8268
|
+
type: String(row.type),
|
|
8269
|
+
id: String(row.id),
|
|
8270
|
+
recordId: String(row.id),
|
|
8271
|
+
name: String(row.name),
|
|
8272
|
+
text: row.content ? `${String(row.name)}\n${String(row.content)}` : String(row.name),
|
|
8273
|
+
scope: parseJson$1(row.scopeJson)
|
|
8274
|
+
}));
|
|
8275
|
+
if (results.length < (input.limit ?? 20)) {
|
|
8276
|
+
const records = await this.#executor.execute({
|
|
8277
|
+
sql: `SELECT f.*,f.scope AS "scopeJson",r.name,r.scope AS "parentScopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" f JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" r ON r.id=f.node AND r.type='node' AND r.mergedInto IS NULL WHERE f.deletedAt IS NULL AND ${visibleSql.replaceAll("scopeKey", "f.scopeKey")} AND lower(f.text) LIKE ? ESCAPE '=' ORDER BY f.id DESC LIMIT ?`,
|
|
8278
|
+
args: [
|
|
8279
|
+
key,
|
|
8280
|
+
key,
|
|
8281
|
+
query,
|
|
8282
|
+
(input.limit ?? 20) - results.length
|
|
8283
|
+
]
|
|
8284
|
+
});
|
|
8285
|
+
results.push(...records.rows.map((row) => {
|
|
8286
|
+
const parentVisible = (0, _mastra_core_storage.isKnowledgeScopeVisible)(parseJson$1(row.parentScopeJson), scope);
|
|
8287
|
+
return {
|
|
8288
|
+
type: "record",
|
|
8289
|
+
id: String(row.id),
|
|
8290
|
+
recordId: String(row.node),
|
|
8291
|
+
name: parentVisible ? String(row.name) : "(private node)",
|
|
8292
|
+
text: String(row.text),
|
|
8293
|
+
scope: parseJson$1(row.scopeJson)
|
|
8294
|
+
};
|
|
8295
|
+
}));
|
|
8296
|
+
}
|
|
8297
|
+
return results;
|
|
8298
|
+
}
|
|
8299
|
+
async getCurationCursor(input) {
|
|
8300
|
+
const row = (await this.#executor.execute({
|
|
8301
|
+
sql: `SELECT * FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS}" WHERE sourceThreadId=? AND agent=?`,
|
|
8302
|
+
args: [input.sourceThreadId, input.agent]
|
|
8303
|
+
})).rows[0];
|
|
8304
|
+
return row ? {
|
|
8305
|
+
sourceThreadId: String(row.sourceThreadId),
|
|
8306
|
+
agent: String(row.agent),
|
|
8307
|
+
lastKnowledgeId: String(row.lastKnowledgeId),
|
|
8308
|
+
updatedAt: toDate$1(row.updatedAt)
|
|
8309
|
+
} : null;
|
|
8310
|
+
}
|
|
8311
|
+
async advanceCurationCursor(input) {
|
|
8312
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
8313
|
+
if ((await this.#executor.execute({
|
|
8314
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS}" (sourceThreadId,agent,lastKnowledgeId,updatedAt) VALUES (?,?,?,?) ON CONFLICT(sourceThreadId,agent) DO UPDATE SET lastKnowledgeId=excluded.lastKnowledgeId,updatedAt=excluded.updatedAt WHERE excluded.lastKnowledgeId >= "${_mastra_core_storage.TABLE_KNOWLEDGE_CURSORS}".lastKnowledgeId`,
|
|
8315
|
+
args: [
|
|
8316
|
+
input.sourceThreadId,
|
|
8317
|
+
input.agent,
|
|
8318
|
+
input.lastKnowledgeId,
|
|
8319
|
+
updatedAt.toISOString()
|
|
8320
|
+
]
|
|
8321
|
+
})).rowsAffected === 0) throw new Error("Knowledge curation cursor cannot move backwards");
|
|
8322
|
+
return {
|
|
8323
|
+
...input,
|
|
8324
|
+
updatedAt
|
|
8325
|
+
};
|
|
8326
|
+
}
|
|
8327
|
+
async listActivity(input) {
|
|
8328
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
8329
|
+
return (await this.#executor.execute({
|
|
8330
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY}" WHERE ${visibleSql}${input.after ? " AND id < ?" : ""} ORDER BY id DESC LIMIT ?`,
|
|
8331
|
+
args: [
|
|
8332
|
+
key,
|
|
8333
|
+
key,
|
|
8334
|
+
...input.after ? [input.after] : [],
|
|
8335
|
+
input.limit ?? 100
|
|
8336
|
+
]
|
|
8337
|
+
})).rows.map((row) => ({
|
|
8338
|
+
id: String(row.id),
|
|
8339
|
+
action: String(row.action),
|
|
8340
|
+
recordType: String(row.recordType),
|
|
8341
|
+
recordId: String(row.recordId),
|
|
8342
|
+
scope: parseJson$1(row.scopeJson),
|
|
8343
|
+
sourceThreadId: row.sourceThreadId == null ? void 0 : String(row.sourceThreadId),
|
|
8344
|
+
createdAt: toDate$1(row.createdAt)
|
|
8345
|
+
}));
|
|
8346
|
+
}
|
|
8347
|
+
async listSemanticOutbox(input = {}) {
|
|
8348
|
+
const clauses = [];
|
|
8349
|
+
const args = [];
|
|
8350
|
+
if (input.status) {
|
|
8351
|
+
clauses.push("status=?");
|
|
8352
|
+
args.push(input.status);
|
|
8353
|
+
}
|
|
8354
|
+
if (input.scope) {
|
|
8355
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
8356
|
+
clauses.push(visibleSql);
|
|
8357
|
+
args.push(key, key);
|
|
8358
|
+
}
|
|
8359
|
+
args.push(input.limit ?? 100);
|
|
8360
|
+
return (await this.#executor.execute({
|
|
8361
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}"${clauses.length ? ` WHERE ${clauses.join(" AND ")}` : ""} ORDER BY createdAt ASC,id ASC LIMIT ?`,
|
|
8362
|
+
args
|
|
8363
|
+
})).rows.map(parseOutbox);
|
|
8364
|
+
}
|
|
8365
|
+
async claimSemanticOutbox(input) {
|
|
8366
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
8367
|
+
const stale = new Date(now.getTime() - (input.claimTimeoutMs ?? 6e4));
|
|
8368
|
+
return this.#transaction(async (tx) => {
|
|
8369
|
+
const clauses = [
|
|
8370
|
+
`availableAt <= ?`,
|
|
8371
|
+
`(status='pending' OR (status='processing' AND claimedAt <= ?))`,
|
|
8372
|
+
`NOT EXISTS (SELECT 1 FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" AS earlier WHERE earlier.documentId = "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".documentId AND earlier.status != 'completed' AND (earlier.createdAt < "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".createdAt OR (earlier.createdAt = "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".createdAt AND earlier.id < "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".id)))`
|
|
8373
|
+
];
|
|
8374
|
+
const args = [now.toISOString(), stale.toISOString()];
|
|
8375
|
+
if (input.scope) {
|
|
8376
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
|
|
8377
|
+
clauses.push(visibleSql);
|
|
8378
|
+
args.push(key, key);
|
|
8379
|
+
}
|
|
8380
|
+
args.push(input.limit ?? 100);
|
|
8381
|
+
const ids = (await tx.execute({
|
|
8382
|
+
sql: `SELECT id FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE ${clauses.join(" AND ")} ORDER BY createdAt ASC,id ASC LIMIT ? FOR UPDATE SKIP LOCKED`,
|
|
8383
|
+
args
|
|
8384
|
+
})).rows.map((row) => String(row.id));
|
|
8385
|
+
for (const id of ids) await tx.execute({
|
|
8386
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='processing',attempts=attempts+1,claimedAt=?,claimedBy=? WHERE id=?`,
|
|
8387
|
+
args: [
|
|
8388
|
+
now.toISOString(),
|
|
8389
|
+
input.workerId,
|
|
8390
|
+
id
|
|
8391
|
+
]
|
|
8392
|
+
});
|
|
8393
|
+
if (!ids.length) return [];
|
|
8394
|
+
return (await tx.execute({
|
|
8395
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE id IN (${ids.map(() => "?").join(",")}) ORDER BY createdAt ASC,id ASC`,
|
|
8396
|
+
args: ids
|
|
8397
|
+
})).rows.map(parseOutbox);
|
|
8398
|
+
});
|
|
8399
|
+
}
|
|
8400
|
+
async completeSemanticOutbox(input) {
|
|
8401
|
+
if (!input.ids.length) return;
|
|
8402
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
8403
|
+
await this.#transaction(async (tx) => {
|
|
8404
|
+
for (const id of input.ids) await tx.execute({
|
|
8405
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='completed',completedAt=? WHERE id=? AND status='processing' AND claimedBy=?`,
|
|
8406
|
+
args: [
|
|
8407
|
+
now,
|
|
8408
|
+
id,
|
|
8409
|
+
input.workerId
|
|
8410
|
+
]
|
|
8411
|
+
});
|
|
8412
|
+
});
|
|
8413
|
+
}
|
|
8414
|
+
async releaseSemanticOutbox(input) {
|
|
8415
|
+
if (!input.ids.length) return;
|
|
8416
|
+
await this.#transaction(async (tx) => {
|
|
8417
|
+
for (const id of input.ids) await tx.execute({
|
|
8418
|
+
sql: `UPDATE "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='pending',availableAt=?,claimedAt=NULL,claimedBy=NULL WHERE id=? AND status='processing' AND claimedBy=?`,
|
|
8419
|
+
args: [
|
|
8420
|
+
(input.retryAt ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
8421
|
+
id,
|
|
8422
|
+
input.workerId
|
|
8423
|
+
]
|
|
8424
|
+
});
|
|
8425
|
+
});
|
|
8426
|
+
}
|
|
8427
|
+
async #transaction(operation) {
|
|
8428
|
+
return this.#client.tx((tx) => operation(createExecutor(tx, this.#schemaName)));
|
|
8429
|
+
}
|
|
8430
|
+
async #getNode(executor, id) {
|
|
8431
|
+
const result = await executor.execute({
|
|
8432
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE id=? AND type='node'`,
|
|
8433
|
+
args: [id]
|
|
8434
|
+
});
|
|
8435
|
+
return result.rows[0] ? parseNode(result.rows[0]) : null;
|
|
8436
|
+
}
|
|
8437
|
+
async #getNodeByName(executor, name, scope) {
|
|
8438
|
+
const result = await executor.execute({
|
|
8439
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" WHERE type='node' AND scopeKey=? AND canonicalName=?`,
|
|
8440
|
+
args: [(0, _mastra_core_storage.knowledgeScopeKey)(scope), canonicalName(name)]
|
|
8441
|
+
});
|
|
8442
|
+
return result.rows[0] ? parseNode(result.rows[0]) : null;
|
|
8443
|
+
}
|
|
8444
|
+
async #resolveNode(executor, name, scope) {
|
|
8445
|
+
for (let length = scope.length; length > 0; length--) {
|
|
8446
|
+
const node = await this.#getNodeByName(executor, name, scope.slice(0, length));
|
|
8447
|
+
if (node) {
|
|
8448
|
+
const terminal = await this.#resolveTerminalNode(executor, node.id);
|
|
8449
|
+
if (terminal && (0, _mastra_core_storage.isKnowledgeScopeVisible)(terminal.scope, scope)) return terminal;
|
|
8450
|
+
}
|
|
8451
|
+
}
|
|
8452
|
+
return null;
|
|
8453
|
+
}
|
|
8454
|
+
async #resolveTerminalNode(executor, id) {
|
|
8455
|
+
let node = await this.#getNode(executor, id);
|
|
8456
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8457
|
+
while (node?.mergedInto) {
|
|
8458
|
+
if (seen.has(node.id)) throw new Error(`Knowledge merge cycle detected at ${node.id}`);
|
|
8459
|
+
seen.add(node.id);
|
|
8460
|
+
node = await this.#getNode(executor, node.mergedInto);
|
|
8461
|
+
}
|
|
8462
|
+
return node;
|
|
8463
|
+
}
|
|
8464
|
+
async #getKnowledge(executor, id, includeDeleted) {
|
|
8465
|
+
const result = await executor.execute({
|
|
8466
|
+
sql: `SELECT *,scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${includeDeleted ? "" : " AND deletedAt IS NULL"}`,
|
|
8467
|
+
args: [id]
|
|
8468
|
+
});
|
|
8469
|
+
return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
|
|
8470
|
+
}
|
|
8471
|
+
async #queryKnowledge(input, relationship) {
|
|
8472
|
+
const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
|
|
8473
|
+
const node = await this.#resolveTerminalNode(this.#executor, nodeReferenceId(input.node));
|
|
8474
|
+
if (!node) return { records: [] };
|
|
8475
|
+
const key = (0, _mastra_core_storage.knowledgeScopeKey)(scope);
|
|
8476
|
+
const args = [
|
|
8477
|
+
node.id,
|
|
8478
|
+
...relationship === "related" ? [node.id] : [],
|
|
8479
|
+
key,
|
|
8480
|
+
key
|
|
8481
|
+
];
|
|
8482
|
+
if (input.after) args.push(input.after);
|
|
8483
|
+
args.push((input.limit ?? 100) + 1);
|
|
8484
|
+
const records = (await this.#executor.execute({
|
|
8485
|
+
sql: `SELECT DISTINCT f.*,f.scope AS "scopeJson" FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS}" f${relationship === "about" ? "" : ` LEFT JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" m ON m.sourceType='record' AND m.sourceId=f.id`} WHERE ${relationship === "about" ? "f.node=?" : relationship === "mentioning" ? "m.recordId=?" : "(f.node=? OR m.recordId=?)"} AND ${visibleSql.replaceAll("scopeKey", "f.scopeKey")}${input.includeDeleted ? "" : " AND f.deletedAt IS NULL"}${input.after ? " AND f.id < ?" : ""} ORDER BY f.id DESC LIMIT ?`,
|
|
8486
|
+
args
|
|
8487
|
+
})).rows.map(parseKnowledge);
|
|
8488
|
+
const limit = input.limit ?? 100;
|
|
8489
|
+
return {
|
|
8490
|
+
records: records.slice(0, limit),
|
|
8491
|
+
nextCursor: records.length > limit ? records[limit - 1]?.id : void 0
|
|
8492
|
+
};
|
|
8493
|
+
}
|
|
8494
|
+
async #replaceMentions(tx, sourceType, sourceId, text, resolutionScope, defaultScope) {
|
|
8495
|
+
await tx.execute({
|
|
8496
|
+
sql: `DELETE FROM "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" WHERE sourceType=? AND sourceId=?`,
|
|
8497
|
+
args: [sourceType, sourceId]
|
|
8498
|
+
});
|
|
8499
|
+
for (const name of (0, _mastra_core_storage.parseKnowledgeWikilinks)(text)) {
|
|
8500
|
+
let node = await this.#resolveNode(tx, name, resolutionScope);
|
|
8501
|
+
if (!node) {
|
|
8502
|
+
node = await this.#getNodeByName(tx, name, defaultScope);
|
|
8503
|
+
if (node) node = await this.#resolveTerminalNode(tx, node.id);
|
|
8504
|
+
if (!node) {
|
|
8505
|
+
const now = /* @__PURE__ */ new Date();
|
|
8506
|
+
node = {
|
|
8507
|
+
id: crypto.randomUUID(),
|
|
8508
|
+
type: "node",
|
|
8509
|
+
name,
|
|
8510
|
+
kind: "node",
|
|
8511
|
+
scope: defaultScope,
|
|
8512
|
+
version: 1,
|
|
8513
|
+
createdAt: now,
|
|
8514
|
+
updatedAt: now
|
|
8515
|
+
};
|
|
8516
|
+
await tx.execute({
|
|
8517
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,NULL,jsonb(?),?,?,NULL,?,?)`,
|
|
8518
|
+
args: [
|
|
8519
|
+
node.id,
|
|
8520
|
+
"node",
|
|
8521
|
+
node.name,
|
|
8522
|
+
canonicalName(node.name),
|
|
8523
|
+
node.kind,
|
|
8524
|
+
JSON.stringify(defaultScope),
|
|
8525
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(defaultScope),
|
|
8526
|
+
1,
|
|
8527
|
+
now.toISOString(),
|
|
8528
|
+
now.toISOString()
|
|
8529
|
+
]
|
|
8530
|
+
});
|
|
8531
|
+
await this.#activity(tx, "node-created", "node", node.id, defaultScope);
|
|
8532
|
+
await this.#outbox(tx, "node", node.id, "upsert", 1, defaultScope);
|
|
8533
|
+
}
|
|
8534
|
+
}
|
|
8535
|
+
await tx.execute({
|
|
8536
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS}" (sourceType,sourceId,recordId) VALUES (?,?,?) ON CONFLICT DO NOTHING`,
|
|
8537
|
+
args: [
|
|
8538
|
+
sourceType,
|
|
8539
|
+
sourceId,
|
|
8540
|
+
node.id
|
|
8541
|
+
]
|
|
8542
|
+
});
|
|
8543
|
+
}
|
|
8544
|
+
}
|
|
8545
|
+
async #activity(executor, action, recordType, recordId, scope, sourceThreadId) {
|
|
8546
|
+
const now = /* @__PURE__ */ new Date();
|
|
8547
|
+
await executor.execute({
|
|
8548
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY}" (id,action,recordType,recordId,scope,scopeKey,sourceThreadId,createdAt) VALUES (?,?,?,?,jsonb(?),?,?,?)`,
|
|
8549
|
+
args: [
|
|
8550
|
+
(0, _mastra_core_storage.createKnowledgeUlid)(),
|
|
8551
|
+
action,
|
|
8552
|
+
recordType,
|
|
8553
|
+
recordId,
|
|
8554
|
+
JSON.stringify(scope),
|
|
8555
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
8556
|
+
sourceThreadId ?? null,
|
|
8557
|
+
now.toISOString()
|
|
8558
|
+
]
|
|
8559
|
+
});
|
|
8560
|
+
}
|
|
8561
|
+
async #outbox(executor, documentType, id, operation, version, scope) {
|
|
8562
|
+
const documentId = (0, _mastra_core_storage.knowledgeSemanticDocumentId)(documentType, id);
|
|
8563
|
+
const idempotencyKey = (0, _mastra_core_storage.knowledgeSemanticIdempotencyKey)(documentId, operation, version);
|
|
8564
|
+
const now = /* @__PURE__ */ new Date();
|
|
8565
|
+
await executor.execute({
|
|
8566
|
+
sql: `INSERT INTO "${_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" (id,idempotencyKey,documentId,documentType,operation,scope,scopeKey,status,attempts,availableAt,claimedAt,claimedBy,createdAt,completedAt) VALUES (?,?,?,?,?,jsonb(?),?,'pending',0,?,NULL,NULL,?,NULL) ON CONFLICT DO NOTHING`,
|
|
8567
|
+
args: [
|
|
8568
|
+
(0, _mastra_core_storage.createKnowledgeUlid)(),
|
|
8569
|
+
idempotencyKey,
|
|
8570
|
+
documentId,
|
|
8571
|
+
documentType,
|
|
8572
|
+
operation,
|
|
8573
|
+
JSON.stringify(scope),
|
|
8574
|
+
(0, _mastra_core_storage.knowledgeScopeKey)(scope),
|
|
8575
|
+
now.toISOString(),
|
|
8576
|
+
now.toISOString()
|
|
8577
|
+
]
|
|
8578
|
+
});
|
|
8579
|
+
}
|
|
8580
|
+
};
|
|
8581
|
+
//#endregion
|
|
7611
8582
|
//#region src/storage/domains/mcp-clients/index.ts
|
|
7612
8583
|
const SNAPSHOT_FIELDS$5 = [
|
|
7613
8584
|
"name",
|
|
@@ -20774,6 +21745,38 @@ var PgFactoryStorageOps = class {
|
|
|
20774
21745
|
* Supports serializable app-table transactions for cross-replica invariant
|
|
20775
21746
|
* enforcement and `authDatabase()` exposing the shared pool.
|
|
20776
21747
|
*/
|
|
21748
|
+
/**
|
|
21749
|
+
* A pool-level `error` listener only covers *idle* clients: pg hands ownership
|
|
21750
|
+
* of a client to the borrower for the duration of a checkout and takes its own
|
|
21751
|
+
* listener off. So a backend restart or network blip that lands on a client
|
|
21752
|
+
* mid-transaction reaches an emitter with no listener, and Node escalates that
|
|
21753
|
+
* to an uncaughtException that kills the process — the pool handler logs the
|
|
21754
|
+
* idle siblings and the borrowed one still brings everything down.
|
|
21755
|
+
*
|
|
21756
|
+
* Attach a listener once per physical connection instead. `connect` fires when
|
|
21757
|
+
* the pool establishes a client, so the client stays covered for its whole life
|
|
21758
|
+
* and there is nothing to remove on release.
|
|
21759
|
+
*
|
|
21760
|
+
* That listener outlives the checkout, so it also sees the failures the pool is
|
|
21761
|
+
* already reporting through its own idle listener. Follow `acquire`/`release`
|
|
21762
|
+
* to tell the two apart and stay quiet while the client is idle — otherwise one
|
|
21763
|
+
* dropped connection is announced twice, the second time as the wrong thing.
|
|
21764
|
+
*
|
|
21765
|
+
* The pool still discards the failed connection; this only keeps the failure
|
|
21766
|
+
* reportable instead of fatal.
|
|
21767
|
+
*/
|
|
21768
|
+
function guardCheckedOutClientErrors(pool, warn = console.warn) {
|
|
21769
|
+
const borrowed = /* @__PURE__ */ new WeakSet();
|
|
21770
|
+
pool.on("connect", (client) => {
|
|
21771
|
+
borrowed.add(client);
|
|
21772
|
+
client.on("error", (err) => {
|
|
21773
|
+
if (!borrowed.has(client)) return;
|
|
21774
|
+
warn(`PgFactoryStorage: client error while checked out (the pool discards this connection): ${err instanceof Error ? err.message : String(err)}`);
|
|
21775
|
+
});
|
|
21776
|
+
});
|
|
21777
|
+
pool.on("acquire", (client) => borrowed.add(client));
|
|
21778
|
+
pool.on("release", (_err, client) => borrowed.delete(client));
|
|
21779
|
+
}
|
|
20777
21780
|
var PgFactoryStorage = class extends _mastra_core_storage.FactoryStorage {
|
|
20778
21781
|
ops;
|
|
20779
21782
|
#pool;
|
|
@@ -20794,6 +21797,7 @@ var PgFactoryStorage = class extends _mastra_core_storage.FactoryStorage {
|
|
|
20794
21797
|
this.#pool.on("error", (err) => {
|
|
20795
21798
|
console.warn(`PgFactoryStorage: idle pool client error (pool discards the client and reconnects on next checkout): ${err instanceof Error ? err.message : String(err)}`);
|
|
20796
21799
|
});
|
|
21800
|
+
guardCheckedOutClientErrors(this.#pool);
|
|
20797
21801
|
}
|
|
20798
21802
|
this.ops = new PgFactoryStorageOps(this.#pool, this.#schemas);
|
|
20799
21803
|
}
|
|
@@ -20923,6 +21927,7 @@ function createHostPool(config) {
|
|
|
20923
21927
|
*/
|
|
20924
21928
|
const ALL_DOMAINS = [
|
|
20925
21929
|
MemoryPG,
|
|
21930
|
+
KnowledgePG,
|
|
20926
21931
|
NotificationsPG,
|
|
20927
21932
|
ObservabilityPG,
|
|
20928
21933
|
ScoresPG,
|
|
@@ -21021,6 +22026,7 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
|
|
|
21021
22026
|
workflows: new WorkflowsPG(domainConfig),
|
|
21022
22027
|
workflowDefinitions: new WorkflowDefinitionsPG(domainConfig),
|
|
21023
22028
|
memory: new MemoryPG(domainConfig),
|
|
22029
|
+
knowledge: new KnowledgePG(domainConfig),
|
|
21024
22030
|
notifications: new NotificationsPG(domainConfig),
|
|
21025
22031
|
observability: new ObservabilityPG(domainConfig),
|
|
21026
22032
|
agents: new AgentsPG(domainConfig),
|
|
@@ -21352,6 +22358,7 @@ exports.ChannelsPG = ChannelsPG;
|
|
|
21352
22358
|
exports.DatasetsPG = DatasetsPG;
|
|
21353
22359
|
exports.ExperimentsPG = ExperimentsPG;
|
|
21354
22360
|
exports.FavoritesPG = FavoritesPG;
|
|
22361
|
+
exports.KnowledgePG = KnowledgePG;
|
|
21355
22362
|
exports.MCPClientsPG = MCPClientsPG;
|
|
21356
22363
|
exports.MCPServersPG = MCPServersPG;
|
|
21357
22364
|
exports.MemoryPG = MemoryPG;
|