@mastra/clickhouse 0.0.0-vector-query-sources-20250516172905 → 0.0.0-vector-query-tool-provider-options-20250828222356
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 +603 -2
- package/LICENSE.md +12 -4
- package/dist/index.cjs +2366 -442
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +3 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2349 -425
- package/dist/index.js.map +1 -0
- package/dist/storage/domains/legacy-evals/index.d.ts +21 -0
- package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +87 -0
- package/dist/storage/domains/memory/index.d.ts.map +1 -0
- package/dist/storage/domains/operations/index.d.ts +42 -0
- package/dist/storage/domains/operations/index.d.ts.map +1 -0
- package/dist/storage/domains/scores/index.d.ts +46 -0
- package/dist/storage/domains/scores/index.d.ts.map +1 -0
- package/dist/storage/domains/traces/index.d.ts +21 -0
- package/dist/storage/domains/traces/index.d.ts.map +1 -0
- package/dist/storage/domains/utils.d.ts +28 -0
- package/dist/storage/domains/utils.d.ts.map +1 -0
- package/dist/storage/domains/workflows/index.d.ts +54 -0
- package/dist/storage/domains/workflows/index.d.ts.map +1 -0
- package/dist/storage/index.d.ts +235 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/package.json +18 -13
- package/src/index.ts +1 -0
- package/src/storage/domains/legacy-evals/index.ts +246 -0
- package/src/storage/domains/memory/index.ts +1473 -0
- package/src/storage/domains/operations/index.ts +319 -0
- package/src/storage/domains/scores/index.ts +351 -0
- package/src/storage/domains/traces/index.ts +275 -0
- package/src/storage/domains/utils.ts +90 -0
- package/src/storage/domains/workflows/index.ts +323 -0
- package/src/storage/index.test.ts +14 -844
- package/src/storage/index.ts +290 -890
- package/tsconfig.build.json +9 -0
- package/tsconfig.json +1 -1
- package/tsup.config.ts +17 -0
- package/dist/_tsup-dts-rollup.d.cts +0 -138
- package/dist/_tsup-dts-rollup.d.ts +0 -138
- package/dist/index.d.cts +0 -4
package/dist/index.cjs
CHANGED
|
@@ -1,22 +1,21 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var client = require('@clickhouse/client');
|
|
4
|
+
var error = require('@mastra/core/error');
|
|
4
5
|
var storage = require('@mastra/core/storage');
|
|
6
|
+
var agent = require('@mastra/core/agent');
|
|
5
7
|
|
|
6
8
|
// src/storage/index.ts
|
|
7
|
-
function safelyParseJSON(jsonString) {
|
|
8
|
-
try {
|
|
9
|
-
return JSON.parse(jsonString);
|
|
10
|
-
} catch {
|
|
11
|
-
return {};
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
9
|
var TABLE_ENGINES = {
|
|
15
10
|
[storage.TABLE_MESSAGES]: `MergeTree()`,
|
|
16
11
|
[storage.TABLE_WORKFLOW_SNAPSHOT]: `ReplacingMergeTree()`,
|
|
17
12
|
[storage.TABLE_TRACES]: `MergeTree()`,
|
|
18
13
|
[storage.TABLE_THREADS]: `ReplacingMergeTree()`,
|
|
19
|
-
[storage.TABLE_EVALS]: `MergeTree()
|
|
14
|
+
[storage.TABLE_EVALS]: `MergeTree()`,
|
|
15
|
+
[storage.TABLE_SCORERS]: `MergeTree()`,
|
|
16
|
+
[storage.TABLE_RESOURCES]: `ReplacingMergeTree()`,
|
|
17
|
+
// TODO: verify this is the correct engine for ai spans when implementing clickhouse storage
|
|
18
|
+
[storage.TABLE_AI_SPANS]: `ReplacingMergeTree()`
|
|
20
19
|
};
|
|
21
20
|
var COLUMN_TYPES = {
|
|
22
21
|
text: "String",
|
|
@@ -24,11 +23,10 @@ var COLUMN_TYPES = {
|
|
|
24
23
|
uuid: "String",
|
|
25
24
|
jsonb: "String",
|
|
26
25
|
integer: "Int64",
|
|
27
|
-
|
|
26
|
+
float: "Float64",
|
|
27
|
+
bigint: "Int64",
|
|
28
|
+
boolean: "Bool"
|
|
28
29
|
};
|
|
29
|
-
function transformRows(rows) {
|
|
30
|
-
return rows.map((row) => transformRow(row));
|
|
31
|
-
}
|
|
32
30
|
function transformRow(row) {
|
|
33
31
|
if (!row) {
|
|
34
32
|
return row;
|
|
@@ -39,33 +37,63 @@ function transformRow(row) {
|
|
|
39
37
|
if (row.updatedAt) {
|
|
40
38
|
row.updatedAt = new Date(row.updatedAt);
|
|
41
39
|
}
|
|
40
|
+
if (row.content && typeof row.content === "string") {
|
|
41
|
+
row.content = storage.safelyParseJSON(row.content);
|
|
42
|
+
}
|
|
42
43
|
return row;
|
|
43
44
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
// This is crucial
|
|
57
|
-
use_client_time_zone: 1,
|
|
58
|
-
output_format_json_quote_64bit_integers: 0
|
|
59
|
-
}
|
|
60
|
-
});
|
|
61
|
-
this.ttl = config.ttl;
|
|
45
|
+
function transformRows(rows) {
|
|
46
|
+
return rows.map((row) => transformRow(row));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/storage/domains/legacy-evals/index.ts
|
|
50
|
+
var LegacyEvalsStorageClickhouse = class extends storage.LegacyEvalsStorage {
|
|
51
|
+
client;
|
|
52
|
+
operations;
|
|
53
|
+
constructor({ client, operations }) {
|
|
54
|
+
super();
|
|
55
|
+
this.client = client;
|
|
56
|
+
this.operations = operations;
|
|
62
57
|
}
|
|
63
58
|
transformEvalRow(row) {
|
|
64
59
|
row = transformRow(row);
|
|
65
|
-
|
|
66
|
-
|
|
60
|
+
let resultValue;
|
|
61
|
+
try {
|
|
62
|
+
if (row.result && typeof row.result === "string" && row.result.trim() !== "") {
|
|
63
|
+
resultValue = JSON.parse(row.result);
|
|
64
|
+
} else if (typeof row.result === "object" && row.result !== null) {
|
|
65
|
+
resultValue = row.result;
|
|
66
|
+
} else if (row.result === null || row.result === void 0 || row.result === "") {
|
|
67
|
+
resultValue = { score: 0 };
|
|
68
|
+
} else {
|
|
69
|
+
throw new Error(`Invalid or empty result field: ${JSON.stringify(row.result)}`);
|
|
70
|
+
}
|
|
71
|
+
} catch (error$1) {
|
|
72
|
+
console.error("Error parsing result field:", row.result, error$1);
|
|
73
|
+
throw new error.MastraError({
|
|
74
|
+
id: "CLICKHOUSE_STORAGE_INVALID_RESULT_FORMAT",
|
|
75
|
+
text: `Invalid result format: ${JSON.stringify(row.result)}`,
|
|
76
|
+
domain: error.ErrorDomain.STORAGE,
|
|
77
|
+
category: error.ErrorCategory.USER
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
let testInfoValue;
|
|
81
|
+
try {
|
|
82
|
+
if (row.test_info && typeof row.test_info === "string" && row.test_info.trim() !== "" && row.test_info !== "null") {
|
|
83
|
+
testInfoValue = JSON.parse(row.test_info);
|
|
84
|
+
} else if (typeof row.test_info === "object" && row.test_info !== null) {
|
|
85
|
+
testInfoValue = row.test_info;
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
testInfoValue = void 0;
|
|
89
|
+
}
|
|
67
90
|
if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
|
|
68
|
-
throw new
|
|
91
|
+
throw new error.MastraError({
|
|
92
|
+
id: "CLICKHOUSE_STORAGE_INVALID_METRIC_FORMAT",
|
|
93
|
+
text: `Invalid MetricResult format: ${JSON.stringify(resultValue)}`,
|
|
94
|
+
domain: error.ErrorDomain.STORAGE,
|
|
95
|
+
category: error.ErrorCategory.USER
|
|
96
|
+
});
|
|
69
97
|
}
|
|
70
98
|
return {
|
|
71
99
|
input: row.input,
|
|
@@ -82,9 +110,9 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
82
110
|
}
|
|
83
111
|
async getEvalsByAgentName(agentName, type) {
|
|
84
112
|
try {
|
|
85
|
-
const baseQuery = `SELECT *, toDateTime64(
|
|
86
|
-
const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND JSONExtractString(test_info, 'testPath') IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR JSONExtractString(test_info, 'testPath') IS NULL)" : "";
|
|
87
|
-
const result = await this.
|
|
113
|
+
const baseQuery = `SELECT *, toDateTime64(created_at, 3) as createdAt FROM ${storage.TABLE_EVALS} WHERE agent_name = {var_agent_name:String}`;
|
|
114
|
+
const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info != 'null' AND JSONExtractString(test_info, 'testPath') IS NOT NULL AND JSONExtractString(test_info, 'testPath') != ''" : type === "live" ? " AND (test_info IS NULL OR test_info = 'null' OR JSONExtractString(test_info, 'testPath') IS NULL OR JSONExtractString(test_info, 'testPath') = '')" : "";
|
|
115
|
+
const result = await this.client.query({
|
|
88
116
|
query: `${baseQuery}${typeCondition} ORDER BY createdAt DESC`,
|
|
89
117
|
query_params: { var_agent_name: agentName },
|
|
90
118
|
clickhouse_settings: {
|
|
@@ -99,126 +127,1349 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
99
127
|
}
|
|
100
128
|
const rows = await result.json();
|
|
101
129
|
return rows.data.map((row) => this.transformEvalRow(row));
|
|
102
|
-
} catch (error) {
|
|
103
|
-
if (error
|
|
130
|
+
} catch (error$1) {
|
|
131
|
+
if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
|
|
104
132
|
return [];
|
|
105
133
|
}
|
|
106
|
-
|
|
107
|
-
|
|
134
|
+
throw new error.MastraError(
|
|
135
|
+
{
|
|
136
|
+
id: "CLICKHOUSE_STORAGE_GET_EVALS_BY_AGENT_FAILED",
|
|
137
|
+
domain: error.ErrorDomain.STORAGE,
|
|
138
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
139
|
+
details: { agentName, type: type ?? null }
|
|
140
|
+
},
|
|
141
|
+
error$1
|
|
142
|
+
);
|
|
108
143
|
}
|
|
109
144
|
}
|
|
110
|
-
async
|
|
145
|
+
async getEvals(options = {}) {
|
|
146
|
+
const { agentName, type, page = 0, perPage = 100, dateRange } = options;
|
|
147
|
+
const fromDate = dateRange?.start;
|
|
148
|
+
const toDate = dateRange?.end;
|
|
149
|
+
const conditions = [];
|
|
150
|
+
if (agentName) {
|
|
151
|
+
conditions.push(`agent_name = {var_agent_name:String}`);
|
|
152
|
+
}
|
|
153
|
+
if (type === "test") {
|
|
154
|
+
conditions.push(
|
|
155
|
+
`(test_info IS NOT NULL AND test_info != 'null' AND JSONExtractString(test_info, 'testPath') IS NOT NULL AND JSONExtractString(test_info, 'testPath') != '')`
|
|
156
|
+
);
|
|
157
|
+
} else if (type === "live") {
|
|
158
|
+
conditions.push(
|
|
159
|
+
`(test_info IS NULL OR test_info = 'null' OR JSONExtractString(test_info, 'testPath') IS NULL OR JSONExtractString(test_info, 'testPath') = '')`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (fromDate) {
|
|
163
|
+
conditions.push(`created_at >= parseDateTime64BestEffort({var_from_date:String})`);
|
|
164
|
+
fromDate.toISOString();
|
|
165
|
+
}
|
|
166
|
+
if (toDate) {
|
|
167
|
+
conditions.push(`created_at <= parseDateTime64BestEffort({var_to_date:String})`);
|
|
168
|
+
toDate.toISOString();
|
|
169
|
+
}
|
|
170
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
111
171
|
try {
|
|
112
|
-
await this.
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
...
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
172
|
+
const countResult = await this.client.query({
|
|
173
|
+
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
|
|
174
|
+
query_params: {
|
|
175
|
+
...agentName ? { var_agent_name: agentName } : {},
|
|
176
|
+
...fromDate ? { var_from_date: fromDate.toISOString() } : {},
|
|
177
|
+
...toDate ? { var_to_date: toDate.toISOString() } : {}
|
|
178
|
+
},
|
|
179
|
+
clickhouse_settings: {
|
|
180
|
+
date_time_input_format: "best_effort",
|
|
181
|
+
date_time_output_format: "iso",
|
|
182
|
+
use_client_time_zone: 1,
|
|
183
|
+
output_format_json_quote_64bit_integers: 0
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
const countData = await countResult.json();
|
|
187
|
+
const total = Number(countData.data?.[0]?.count ?? 0);
|
|
188
|
+
const currentOffset = page * perPage;
|
|
189
|
+
const hasMore = currentOffset + perPage < total;
|
|
190
|
+
if (total === 0) {
|
|
191
|
+
return {
|
|
192
|
+
evals: [],
|
|
193
|
+
total: 0,
|
|
194
|
+
page,
|
|
195
|
+
perPage,
|
|
196
|
+
hasMore: false
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const dataResult = await this.client.query({
|
|
200
|
+
query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT {var_limit:UInt32} OFFSET {var_offset:UInt32}`,
|
|
201
|
+
query_params: {
|
|
202
|
+
...agentName ? { var_agent_name: agentName } : {},
|
|
203
|
+
...fromDate ? { var_from_date: fromDate.toISOString() } : {},
|
|
204
|
+
...toDate ? { var_to_date: toDate.toISOString() } : {},
|
|
205
|
+
var_limit: perPage || 100,
|
|
206
|
+
var_offset: currentOffset || 0
|
|
207
|
+
},
|
|
123
208
|
clickhouse_settings: {
|
|
124
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
125
209
|
date_time_input_format: "best_effort",
|
|
210
|
+
date_time_output_format: "iso",
|
|
126
211
|
use_client_time_zone: 1,
|
|
127
212
|
output_format_json_quote_64bit_integers: 0
|
|
128
213
|
}
|
|
129
214
|
});
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
215
|
+
const rows = await dataResult.json();
|
|
216
|
+
return {
|
|
217
|
+
evals: rows.data.map((row) => this.transformEvalRow(row)),
|
|
218
|
+
total,
|
|
219
|
+
page,
|
|
220
|
+
perPage,
|
|
221
|
+
hasMore
|
|
222
|
+
};
|
|
223
|
+
} catch (error$1) {
|
|
224
|
+
if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
|
|
225
|
+
return {
|
|
226
|
+
evals: [],
|
|
227
|
+
total: 0,
|
|
228
|
+
page,
|
|
229
|
+
perPage,
|
|
230
|
+
hasMore: false
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
throw new error.MastraError(
|
|
234
|
+
{
|
|
235
|
+
id: "CLICKHOUSE_STORAGE_GET_EVALS_FAILED",
|
|
236
|
+
domain: error.ErrorDomain.STORAGE,
|
|
237
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
238
|
+
details: { agentName: agentName ?? "all", type: type ?? "all" }
|
|
239
|
+
},
|
|
240
|
+
error$1
|
|
241
|
+
);
|
|
133
242
|
}
|
|
134
243
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
244
|
+
};
|
|
245
|
+
var MemoryStorageClickhouse = class extends storage.MemoryStorage {
|
|
246
|
+
client;
|
|
247
|
+
operations;
|
|
248
|
+
constructor({ client, operations }) {
|
|
249
|
+
super();
|
|
250
|
+
this.client = client;
|
|
251
|
+
this.operations = operations;
|
|
252
|
+
}
|
|
253
|
+
async getMessages({
|
|
254
|
+
threadId,
|
|
255
|
+
resourceId,
|
|
256
|
+
selectBy,
|
|
257
|
+
format
|
|
144
258
|
}) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
259
|
+
try {
|
|
260
|
+
const messages = [];
|
|
261
|
+
const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
|
|
262
|
+
const include = selectBy?.include || [];
|
|
263
|
+
if (include.length) {
|
|
264
|
+
const unionQueries = [];
|
|
265
|
+
const params = [];
|
|
266
|
+
let paramIdx = 1;
|
|
267
|
+
for (const inc of include) {
|
|
268
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
269
|
+
const searchId = inc.threadId || threadId;
|
|
270
|
+
unionQueries.push(`
|
|
271
|
+
SELECT * FROM (
|
|
272
|
+
WITH numbered_messages AS (
|
|
273
|
+
SELECT
|
|
274
|
+
id, content, role, type, "createdAt", thread_id, "resourceId",
|
|
275
|
+
ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
|
|
276
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
277
|
+
WHERE thread_id = {var_thread_id_${paramIdx}:String}
|
|
278
|
+
),
|
|
279
|
+
target_positions AS (
|
|
280
|
+
SELECT row_num as target_pos
|
|
281
|
+
FROM numbered_messages
|
|
282
|
+
WHERE id = {var_include_id_${paramIdx}:String}
|
|
283
|
+
)
|
|
284
|
+
SELECT DISTINCT m.id, m.content, m.role, m.type, m."createdAt", m.thread_id AS "threadId"
|
|
285
|
+
FROM numbered_messages m
|
|
286
|
+
CROSS JOIN target_positions t
|
|
287
|
+
WHERE m.row_num BETWEEN (t.target_pos - {var_withPreviousMessages_${paramIdx}:Int64}) AND (t.target_pos + {var_withNextMessages_${paramIdx}:Int64})
|
|
288
|
+
) AS query_${paramIdx}
|
|
289
|
+
`);
|
|
290
|
+
params.push(
|
|
291
|
+
{ [`var_thread_id_${paramIdx}`]: searchId },
|
|
292
|
+
{ [`var_include_id_${paramIdx}`]: id },
|
|
293
|
+
{ [`var_withPreviousMessages_${paramIdx}`]: withPreviousMessages },
|
|
294
|
+
{ [`var_withNextMessages_${paramIdx}`]: withNextMessages }
|
|
295
|
+
);
|
|
296
|
+
paramIdx++;
|
|
297
|
+
}
|
|
298
|
+
const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" DESC';
|
|
299
|
+
const mergedParams = params.reduce((acc, paramObj) => ({ ...acc, ...paramObj }), {});
|
|
300
|
+
const includeResult = await this.client.query({
|
|
301
|
+
query: finalQuery,
|
|
302
|
+
query_params: mergedParams,
|
|
303
|
+
clickhouse_settings: {
|
|
304
|
+
date_time_input_format: "best_effort",
|
|
305
|
+
date_time_output_format: "iso",
|
|
306
|
+
use_client_time_zone: 1,
|
|
307
|
+
output_format_json_quote_64bit_integers: 0
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
const rows2 = await includeResult.json();
|
|
311
|
+
const includedMessages = transformRows(rows2.data);
|
|
312
|
+
const seen = /* @__PURE__ */ new Set();
|
|
313
|
+
const dedupedMessages = includedMessages.filter((message) => {
|
|
314
|
+
if (seen.has(message.id)) return false;
|
|
315
|
+
seen.add(message.id);
|
|
316
|
+
return true;
|
|
317
|
+
});
|
|
318
|
+
messages.push(...dedupedMessages);
|
|
319
|
+
}
|
|
320
|
+
const result = await this.client.query({
|
|
321
|
+
query: `
|
|
322
|
+
SELECT
|
|
323
|
+
id,
|
|
324
|
+
content,
|
|
325
|
+
role,
|
|
326
|
+
type,
|
|
327
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
328
|
+
thread_id AS "threadId"
|
|
329
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
330
|
+
WHERE thread_id = {threadId:String}
|
|
331
|
+
AND id NOT IN ({exclude:Array(String)})
|
|
332
|
+
ORDER BY "createdAt" DESC
|
|
333
|
+
LIMIT {limit:Int64}
|
|
334
|
+
`,
|
|
335
|
+
query_params: {
|
|
336
|
+
threadId,
|
|
337
|
+
exclude: messages.map((m) => m.id),
|
|
338
|
+
limit
|
|
339
|
+
},
|
|
340
|
+
clickhouse_settings: {
|
|
341
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
342
|
+
date_time_input_format: "best_effort",
|
|
343
|
+
date_time_output_format: "iso",
|
|
344
|
+
use_client_time_zone: 1,
|
|
345
|
+
output_format_json_quote_64bit_integers: 0
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
const rows = await result.json();
|
|
349
|
+
messages.push(...transformRows(rows.data));
|
|
350
|
+
messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
351
|
+
messages.forEach((message) => {
|
|
352
|
+
if (typeof message.content === "string") {
|
|
353
|
+
try {
|
|
354
|
+
message.content = JSON.parse(message.content);
|
|
355
|
+
} catch {
|
|
356
|
+
}
|
|
357
|
+
}
|
|
161
358
|
});
|
|
359
|
+
const list = new agent.MessageList({ threadId, resourceId }).add(messages, "memory");
|
|
360
|
+
if (format === `v2`) return list.get.all.v2();
|
|
361
|
+
return list.get.all.v1();
|
|
362
|
+
} catch (error$1) {
|
|
363
|
+
throw new error.MastraError(
|
|
364
|
+
{
|
|
365
|
+
id: "CLICKHOUSE_STORAGE_GET_MESSAGES_FAILED",
|
|
366
|
+
domain: error.ErrorDomain.STORAGE,
|
|
367
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
368
|
+
details: { threadId, resourceId: resourceId ?? "" }
|
|
369
|
+
},
|
|
370
|
+
error$1
|
|
371
|
+
);
|
|
162
372
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
373
|
+
}
|
|
374
|
+
async getMessagesById({
|
|
375
|
+
messageIds,
|
|
376
|
+
format
|
|
377
|
+
}) {
|
|
378
|
+
if (messageIds.length === 0) return [];
|
|
379
|
+
try {
|
|
380
|
+
const result = await this.client.query({
|
|
381
|
+
query: `
|
|
382
|
+
SELECT
|
|
383
|
+
id,
|
|
384
|
+
content,
|
|
385
|
+
role,
|
|
386
|
+
type,
|
|
387
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
388
|
+
thread_id AS "threadId",
|
|
389
|
+
"resourceId"
|
|
390
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
391
|
+
WHERE id IN {messageIds:Array(String)}
|
|
392
|
+
ORDER BY "createdAt" DESC
|
|
393
|
+
`,
|
|
394
|
+
query_params: {
|
|
395
|
+
messageIds
|
|
396
|
+
},
|
|
397
|
+
clickhouse_settings: {
|
|
398
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
399
|
+
date_time_input_format: "best_effort",
|
|
400
|
+
date_time_output_format: "iso",
|
|
401
|
+
use_client_time_zone: 1,
|
|
402
|
+
output_format_json_quote_64bit_integers: 0
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
const rows = await result.json();
|
|
406
|
+
const messages = transformRows(rows.data);
|
|
407
|
+
messages.forEach((message) => {
|
|
408
|
+
if (typeof message.content === "string") {
|
|
409
|
+
try {
|
|
410
|
+
message.content = JSON.parse(message.content);
|
|
411
|
+
} catch {
|
|
412
|
+
}
|
|
413
|
+
}
|
|
169
414
|
});
|
|
415
|
+
const list = new agent.MessageList().add(messages, "memory");
|
|
416
|
+
if (format === `v1`) return list.get.all.v1();
|
|
417
|
+
return list.get.all.v2();
|
|
418
|
+
} catch (error$1) {
|
|
419
|
+
throw new error.MastraError(
|
|
420
|
+
{
|
|
421
|
+
id: "CLICKHOUSE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
|
|
422
|
+
domain: error.ErrorDomain.STORAGE,
|
|
423
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
424
|
+
details: { messageIds: JSON.stringify(messageIds) }
|
|
425
|
+
},
|
|
426
|
+
error$1
|
|
427
|
+
);
|
|
170
428
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
429
|
+
}
|
|
430
|
+
async saveMessages(args) {
|
|
431
|
+
const { messages, format = "v1" } = args;
|
|
432
|
+
if (messages.length === 0) return messages;
|
|
433
|
+
for (const message of messages) {
|
|
434
|
+
const resourceId = message.resourceId;
|
|
435
|
+
if (!resourceId) {
|
|
436
|
+
throw new Error("Resource ID is required");
|
|
437
|
+
}
|
|
438
|
+
if (!message.threadId) {
|
|
439
|
+
throw new Error("Thread ID is required");
|
|
440
|
+
}
|
|
441
|
+
const thread = await this.getThreadById({ threadId: message.threadId });
|
|
442
|
+
if (!thread) {
|
|
443
|
+
throw new Error(`Thread ${message.threadId} not found`);
|
|
444
|
+
}
|
|
174
445
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
446
|
+
const threadIdSet = /* @__PURE__ */ new Map();
|
|
447
|
+
await Promise.all(
|
|
448
|
+
messages.map(async (m) => {
|
|
449
|
+
const resourceId = m.resourceId;
|
|
450
|
+
if (!resourceId) {
|
|
451
|
+
throw new Error("Resource ID is required");
|
|
452
|
+
}
|
|
453
|
+
if (!m.threadId) {
|
|
454
|
+
throw new Error("Thread ID is required");
|
|
455
|
+
}
|
|
456
|
+
const thread = await this.getThreadById({ threadId: m.threadId });
|
|
457
|
+
if (!thread) {
|
|
458
|
+
throw new Error(`Thread ${m.threadId} not found`);
|
|
459
|
+
}
|
|
460
|
+
threadIdSet.set(m.threadId, thread);
|
|
461
|
+
})
|
|
462
|
+
);
|
|
463
|
+
try {
|
|
464
|
+
const existingResult = await this.client.query({
|
|
465
|
+
query: `SELECT id, thread_id FROM ${storage.TABLE_MESSAGES} WHERE id IN ({ids:Array(String)})`,
|
|
466
|
+
query_params: {
|
|
467
|
+
ids: messages.map((m) => m.id)
|
|
468
|
+
},
|
|
469
|
+
clickhouse_settings: {
|
|
470
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
471
|
+
date_time_input_format: "best_effort",
|
|
472
|
+
date_time_output_format: "iso",
|
|
473
|
+
use_client_time_zone: 1,
|
|
474
|
+
output_format_json_quote_64bit_integers: 0
|
|
475
|
+
},
|
|
476
|
+
format: "JSONEachRow"
|
|
477
|
+
});
|
|
478
|
+
const existingRows = await existingResult.json();
|
|
479
|
+
const existingSet = new Set(existingRows.map((row) => `${row.id}::${row.thread_id}`));
|
|
480
|
+
const toInsert = messages.filter((m) => !existingSet.has(`${m.id}::${m.threadId}`));
|
|
481
|
+
const toUpdate = messages.filter((m) => existingSet.has(`${m.id}::${m.threadId}`));
|
|
482
|
+
const toMove = messages.filter((m) => {
|
|
483
|
+
const existingRow = existingRows.find((row) => row.id === m.id);
|
|
484
|
+
return existingRow && existingRow.thread_id !== m.threadId;
|
|
485
|
+
});
|
|
486
|
+
const deletePromises = toMove.map((message) => {
|
|
487
|
+
const existingRow = existingRows.find((row) => row.id === message.id);
|
|
488
|
+
if (!existingRow) return Promise.resolve();
|
|
489
|
+
return this.client.command({
|
|
490
|
+
query: `DELETE FROM ${storage.TABLE_MESSAGES} WHERE id = {var_id:String} AND thread_id = {var_old_thread_id:String}`,
|
|
491
|
+
query_params: {
|
|
492
|
+
var_id: message.id,
|
|
493
|
+
var_old_thread_id: existingRow.thread_id
|
|
494
|
+
},
|
|
495
|
+
clickhouse_settings: {
|
|
496
|
+
date_time_input_format: "best_effort",
|
|
497
|
+
use_client_time_zone: 1,
|
|
498
|
+
output_format_json_quote_64bit_integers: 0
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
});
|
|
502
|
+
const updatePromises = toUpdate.map(
|
|
503
|
+
(message) => this.client.command({
|
|
504
|
+
query: `
|
|
505
|
+
ALTER TABLE ${storage.TABLE_MESSAGES}
|
|
506
|
+
UPDATE content = {var_content:String}, role = {var_role:String}, type = {var_type:String}, resourceId = {var_resourceId:String}
|
|
507
|
+
WHERE id = {var_id:String} AND thread_id = {var_thread_id:String}
|
|
508
|
+
`,
|
|
509
|
+
query_params: {
|
|
510
|
+
var_content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
511
|
+
var_role: message.role,
|
|
512
|
+
var_type: message.type || "v2",
|
|
513
|
+
var_resourceId: message.resourceId,
|
|
514
|
+
var_id: message.id,
|
|
515
|
+
var_thread_id: message.threadId
|
|
516
|
+
},
|
|
517
|
+
clickhouse_settings: {
|
|
518
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
519
|
+
date_time_input_format: "best_effort",
|
|
520
|
+
use_client_time_zone: 1,
|
|
521
|
+
output_format_json_quote_64bit_integers: 0
|
|
522
|
+
}
|
|
523
|
+
})
|
|
524
|
+
);
|
|
525
|
+
await Promise.all([
|
|
526
|
+
// Insert new messages (including moved messages)
|
|
527
|
+
this.client.insert({
|
|
528
|
+
table: storage.TABLE_MESSAGES,
|
|
529
|
+
format: "JSONEachRow",
|
|
530
|
+
values: toInsert.map((message) => ({
|
|
531
|
+
id: message.id,
|
|
532
|
+
thread_id: message.threadId,
|
|
533
|
+
resourceId: message.resourceId,
|
|
534
|
+
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
535
|
+
createdAt: message.createdAt.toISOString(),
|
|
536
|
+
role: message.role,
|
|
537
|
+
type: message.type || "v2"
|
|
538
|
+
})),
|
|
539
|
+
clickhouse_settings: {
|
|
540
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
541
|
+
date_time_input_format: "best_effort",
|
|
542
|
+
use_client_time_zone: 1,
|
|
543
|
+
output_format_json_quote_64bit_integers: 0
|
|
544
|
+
}
|
|
545
|
+
}),
|
|
546
|
+
...updatePromises,
|
|
547
|
+
...deletePromises,
|
|
548
|
+
// Update thread's updatedAt timestamp
|
|
549
|
+
this.client.insert({
|
|
550
|
+
table: storage.TABLE_THREADS,
|
|
551
|
+
format: "JSONEachRow",
|
|
552
|
+
values: Array.from(threadIdSet.values()).map((thread) => ({
|
|
553
|
+
id: thread.id,
|
|
554
|
+
resourceId: thread.resourceId,
|
|
555
|
+
title: thread.title,
|
|
556
|
+
metadata: thread.metadata,
|
|
557
|
+
createdAt: thread.createdAt,
|
|
558
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
559
|
+
})),
|
|
560
|
+
clickhouse_settings: {
|
|
561
|
+
date_time_input_format: "best_effort",
|
|
562
|
+
use_client_time_zone: 1,
|
|
563
|
+
output_format_json_quote_64bit_integers: 0
|
|
564
|
+
}
|
|
565
|
+
})
|
|
566
|
+
]);
|
|
567
|
+
const list = new agent.MessageList().add(messages, "memory");
|
|
568
|
+
if (format === `v2`) return list.get.all.v2();
|
|
569
|
+
return list.get.all.v1();
|
|
570
|
+
} catch (error$1) {
|
|
571
|
+
throw new error.MastraError(
|
|
572
|
+
{
|
|
573
|
+
id: "CLICKHOUSE_STORAGE_SAVE_MESSAGES_FAILED",
|
|
574
|
+
domain: error.ErrorDomain.STORAGE,
|
|
575
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
576
|
+
},
|
|
577
|
+
error$1
|
|
578
|
+
);
|
|
178
579
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
580
|
+
}
|
|
581
|
+
async getThreadById({ threadId }) {
|
|
582
|
+
try {
|
|
583
|
+
const result = await this.client.query({
|
|
584
|
+
query: `SELECT
|
|
585
|
+
id,
|
|
586
|
+
"resourceId",
|
|
587
|
+
title,
|
|
588
|
+
metadata,
|
|
589
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
590
|
+
toDateTime64(updatedAt, 3) as updatedAt
|
|
591
|
+
FROM "${storage.TABLE_THREADS}"
|
|
592
|
+
FINAL
|
|
593
|
+
WHERE id = {var_id:String}`,
|
|
594
|
+
query_params: { var_id: threadId },
|
|
595
|
+
clickhouse_settings: {
|
|
596
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
597
|
+
date_time_input_format: "best_effort",
|
|
598
|
+
date_time_output_format: "iso",
|
|
599
|
+
use_client_time_zone: 1,
|
|
600
|
+
output_format_json_quote_64bit_integers: 0
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
const rows = await result.json();
|
|
604
|
+
const thread = transformRow(rows.data[0]);
|
|
605
|
+
if (!thread) {
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
return {
|
|
609
|
+
...thread,
|
|
610
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
611
|
+
createdAt: thread.createdAt,
|
|
612
|
+
updatedAt: thread.updatedAt
|
|
613
|
+
};
|
|
614
|
+
} catch (error$1) {
|
|
615
|
+
throw new error.MastraError(
|
|
616
|
+
{
|
|
617
|
+
id: "CLICKHOUSE_STORAGE_GET_THREAD_BY_ID_FAILED",
|
|
618
|
+
domain: error.ErrorDomain.STORAGE,
|
|
619
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
620
|
+
details: { threadId }
|
|
621
|
+
},
|
|
622
|
+
error$1
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
627
|
+
try {
|
|
628
|
+
const result = await this.client.query({
|
|
629
|
+
query: `SELECT
|
|
630
|
+
id,
|
|
631
|
+
"resourceId",
|
|
632
|
+
title,
|
|
633
|
+
metadata,
|
|
634
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
635
|
+
toDateTime64(updatedAt, 3) as updatedAt
|
|
636
|
+
FROM "${storage.TABLE_THREADS}"
|
|
637
|
+
WHERE "resourceId" = {var_resourceId:String}`,
|
|
638
|
+
query_params: { var_resourceId: resourceId },
|
|
639
|
+
clickhouse_settings: {
|
|
640
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
641
|
+
date_time_input_format: "best_effort",
|
|
642
|
+
date_time_output_format: "iso",
|
|
643
|
+
use_client_time_zone: 1,
|
|
644
|
+
output_format_json_quote_64bit_integers: 0
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
const rows = await result.json();
|
|
648
|
+
const threads = transformRows(rows.data);
|
|
649
|
+
return threads.map((thread) => ({
|
|
650
|
+
...thread,
|
|
651
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
652
|
+
createdAt: thread.createdAt,
|
|
653
|
+
updatedAt: thread.updatedAt
|
|
654
|
+
}));
|
|
655
|
+
} catch (error$1) {
|
|
656
|
+
throw new error.MastraError(
|
|
657
|
+
{
|
|
658
|
+
id: "CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
|
|
659
|
+
domain: error.ErrorDomain.STORAGE,
|
|
660
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
661
|
+
details: { resourceId }
|
|
662
|
+
},
|
|
663
|
+
error$1
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
async saveThread({ thread }) {
|
|
668
|
+
try {
|
|
669
|
+
await this.client.insert({
|
|
670
|
+
table: storage.TABLE_THREADS,
|
|
671
|
+
values: [
|
|
672
|
+
{
|
|
673
|
+
...thread,
|
|
674
|
+
createdAt: thread.createdAt.toISOString(),
|
|
675
|
+
updatedAt: thread.updatedAt.toISOString()
|
|
676
|
+
}
|
|
677
|
+
],
|
|
678
|
+
format: "JSONEachRow",
|
|
679
|
+
clickhouse_settings: {
|
|
680
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
681
|
+
date_time_input_format: "best_effort",
|
|
682
|
+
use_client_time_zone: 1,
|
|
683
|
+
output_format_json_quote_64bit_integers: 0
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
return thread;
|
|
687
|
+
} catch (error$1) {
|
|
688
|
+
throw new error.MastraError(
|
|
689
|
+
{
|
|
690
|
+
id: "CLICKHOUSE_STORAGE_SAVE_THREAD_FAILED",
|
|
691
|
+
domain: error.ErrorDomain.STORAGE,
|
|
692
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
693
|
+
details: { threadId: thread.id }
|
|
694
|
+
},
|
|
695
|
+
error$1
|
|
696
|
+
);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
async updateThread({
|
|
700
|
+
id,
|
|
701
|
+
title,
|
|
702
|
+
metadata
|
|
703
|
+
}) {
|
|
704
|
+
try {
|
|
705
|
+
const existingThread = await this.getThreadById({ threadId: id });
|
|
706
|
+
if (!existingThread) {
|
|
707
|
+
throw new Error(`Thread ${id} not found`);
|
|
708
|
+
}
|
|
709
|
+
const mergedMetadata = {
|
|
710
|
+
...existingThread.metadata,
|
|
711
|
+
...metadata
|
|
712
|
+
};
|
|
713
|
+
const updatedThread = {
|
|
714
|
+
...existingThread,
|
|
715
|
+
title,
|
|
716
|
+
metadata: mergedMetadata,
|
|
717
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
718
|
+
};
|
|
719
|
+
await this.client.insert({
|
|
720
|
+
table: storage.TABLE_THREADS,
|
|
721
|
+
format: "JSONEachRow",
|
|
722
|
+
values: [
|
|
723
|
+
{
|
|
724
|
+
id: updatedThread.id,
|
|
725
|
+
resourceId: updatedThread.resourceId,
|
|
726
|
+
title: updatedThread.title,
|
|
727
|
+
metadata: updatedThread.metadata,
|
|
728
|
+
createdAt: updatedThread.createdAt,
|
|
729
|
+
updatedAt: updatedThread.updatedAt.toISOString()
|
|
730
|
+
}
|
|
731
|
+
],
|
|
732
|
+
clickhouse_settings: {
|
|
733
|
+
date_time_input_format: "best_effort",
|
|
734
|
+
use_client_time_zone: 1,
|
|
735
|
+
output_format_json_quote_64bit_integers: 0
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
return updatedThread;
|
|
739
|
+
} catch (error$1) {
|
|
740
|
+
throw new error.MastraError(
|
|
741
|
+
{
|
|
742
|
+
id: "CLICKHOUSE_STORAGE_UPDATE_THREAD_FAILED",
|
|
743
|
+
domain: error.ErrorDomain.STORAGE,
|
|
744
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
745
|
+
details: { threadId: id, title }
|
|
746
|
+
},
|
|
747
|
+
error$1
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
async deleteThread({ threadId }) {
|
|
752
|
+
try {
|
|
753
|
+
await this.client.command({
|
|
754
|
+
query: `DELETE FROM "${storage.TABLE_MESSAGES}" WHERE thread_id = {var_thread_id:String};`,
|
|
755
|
+
query_params: { var_thread_id: threadId },
|
|
756
|
+
clickhouse_settings: {
|
|
757
|
+
output_format_json_quote_64bit_integers: 0
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
await this.client.command({
|
|
761
|
+
query: `DELETE FROM "${storage.TABLE_THREADS}" WHERE id = {var_id:String};`,
|
|
762
|
+
query_params: { var_id: threadId },
|
|
763
|
+
clickhouse_settings: {
|
|
764
|
+
output_format_json_quote_64bit_integers: 0
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
} catch (error$1) {
|
|
768
|
+
throw new error.MastraError(
|
|
769
|
+
{
|
|
770
|
+
id: "CLICKHOUSE_STORAGE_DELETE_THREAD_FAILED",
|
|
771
|
+
domain: error.ErrorDomain.STORAGE,
|
|
772
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
773
|
+
details: { threadId }
|
|
774
|
+
},
|
|
775
|
+
error$1
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
780
|
+
const { resourceId, page = 0, perPage = 100 } = args;
|
|
781
|
+
try {
|
|
782
|
+
const currentOffset = page * perPage;
|
|
783
|
+
const countResult = await this.client.query({
|
|
784
|
+
query: `SELECT count() as total FROM ${storage.TABLE_THREADS} WHERE resourceId = {resourceId:String}`,
|
|
785
|
+
query_params: { resourceId },
|
|
786
|
+
clickhouse_settings: {
|
|
787
|
+
date_time_input_format: "best_effort",
|
|
788
|
+
date_time_output_format: "iso",
|
|
789
|
+
use_client_time_zone: 1,
|
|
790
|
+
output_format_json_quote_64bit_integers: 0
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
const countData = await countResult.json();
|
|
794
|
+
const total = countData.data[0].total;
|
|
795
|
+
if (total === 0) {
|
|
796
|
+
return {
|
|
797
|
+
threads: [],
|
|
798
|
+
total: 0,
|
|
799
|
+
page,
|
|
800
|
+
perPage,
|
|
801
|
+
hasMore: false
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
const dataResult = await this.client.query({
|
|
805
|
+
query: `
|
|
806
|
+
SELECT
|
|
807
|
+
id,
|
|
808
|
+
resourceId,
|
|
809
|
+
title,
|
|
810
|
+
metadata,
|
|
811
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
812
|
+
toDateTime64(updatedAt, 3) as updatedAt
|
|
813
|
+
FROM ${storage.TABLE_THREADS}
|
|
814
|
+
WHERE resourceId = {resourceId:String}
|
|
815
|
+
ORDER BY createdAt DESC
|
|
816
|
+
LIMIT {limit:Int64} OFFSET {offset:Int64}
|
|
817
|
+
`,
|
|
818
|
+
query_params: {
|
|
819
|
+
resourceId,
|
|
820
|
+
limit: perPage,
|
|
821
|
+
offset: currentOffset
|
|
822
|
+
},
|
|
823
|
+
clickhouse_settings: {
|
|
824
|
+
date_time_input_format: "best_effort",
|
|
825
|
+
date_time_output_format: "iso",
|
|
826
|
+
use_client_time_zone: 1,
|
|
827
|
+
output_format_json_quote_64bit_integers: 0
|
|
828
|
+
}
|
|
829
|
+
});
|
|
830
|
+
const rows = await dataResult.json();
|
|
831
|
+
const threads = transformRows(rows.data);
|
|
832
|
+
return {
|
|
833
|
+
threads,
|
|
834
|
+
total,
|
|
835
|
+
page,
|
|
836
|
+
perPage,
|
|
837
|
+
hasMore: currentOffset + threads.length < total
|
|
838
|
+
};
|
|
839
|
+
} catch (error$1) {
|
|
840
|
+
throw new error.MastraError(
|
|
841
|
+
{
|
|
842
|
+
id: "CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
|
|
843
|
+
domain: error.ErrorDomain.STORAGE,
|
|
844
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
845
|
+
details: { resourceId, page }
|
|
846
|
+
},
|
|
847
|
+
error$1
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
async getMessagesPaginated(args) {
|
|
852
|
+
try {
|
|
853
|
+
const { threadId, selectBy, format = "v1" } = args;
|
|
854
|
+
const page = selectBy?.pagination?.page || 0;
|
|
855
|
+
const perPageInput = selectBy?.pagination?.perPage;
|
|
856
|
+
const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 20 });
|
|
857
|
+
const offset = page * perPage;
|
|
858
|
+
const dateRange = selectBy?.pagination?.dateRange;
|
|
859
|
+
const fromDate = dateRange?.start;
|
|
860
|
+
const toDate = dateRange?.end;
|
|
861
|
+
const messages = [];
|
|
862
|
+
if (selectBy?.include?.length) {
|
|
863
|
+
const include = selectBy.include;
|
|
864
|
+
const unionQueries = [];
|
|
865
|
+
const params = [];
|
|
866
|
+
let paramIdx = 1;
|
|
867
|
+
for (const inc of include) {
|
|
868
|
+
const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
|
|
869
|
+
const searchId = inc.threadId || threadId;
|
|
870
|
+
unionQueries.push(`
|
|
871
|
+
SELECT * FROM (
|
|
872
|
+
WITH numbered_messages AS (
|
|
873
|
+
SELECT
|
|
874
|
+
id, content, role, type, "createdAt", thread_id, "resourceId",
|
|
875
|
+
ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
|
|
876
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
877
|
+
WHERE thread_id = {var_thread_id_${paramIdx}:String}
|
|
878
|
+
),
|
|
879
|
+
target_positions AS (
|
|
880
|
+
SELECT row_num as target_pos
|
|
881
|
+
FROM numbered_messages
|
|
882
|
+
WHERE id = {var_include_id_${paramIdx}:String}
|
|
883
|
+
)
|
|
884
|
+
SELECT DISTINCT m.id, m.content, m.role, m.type, m."createdAt", m.thread_id AS "threadId"
|
|
885
|
+
FROM numbered_messages m
|
|
886
|
+
CROSS JOIN target_positions t
|
|
887
|
+
WHERE m.row_num BETWEEN (t.target_pos - {var_withPreviousMessages_${paramIdx}:Int64}) AND (t.target_pos + {var_withNextMessages_${paramIdx}:Int64})
|
|
888
|
+
) AS query_${paramIdx}
|
|
889
|
+
`);
|
|
890
|
+
params.push(
|
|
891
|
+
{ [`var_thread_id_${paramIdx}`]: searchId },
|
|
892
|
+
{ [`var_include_id_${paramIdx}`]: id },
|
|
893
|
+
{ [`var_withPreviousMessages_${paramIdx}`]: withPreviousMessages },
|
|
894
|
+
{ [`var_withNextMessages_${paramIdx}`]: withNextMessages }
|
|
895
|
+
);
|
|
896
|
+
paramIdx++;
|
|
897
|
+
}
|
|
898
|
+
const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" DESC';
|
|
899
|
+
const mergedParams = params.reduce((acc, paramObj) => ({ ...acc, ...paramObj }), {});
|
|
900
|
+
const includeResult = await this.client.query({
|
|
901
|
+
query: finalQuery,
|
|
902
|
+
query_params: mergedParams,
|
|
903
|
+
clickhouse_settings: {
|
|
904
|
+
date_time_input_format: "best_effort",
|
|
905
|
+
date_time_output_format: "iso",
|
|
906
|
+
use_client_time_zone: 1,
|
|
907
|
+
output_format_json_quote_64bit_integers: 0
|
|
908
|
+
}
|
|
909
|
+
});
|
|
910
|
+
const rows2 = await includeResult.json();
|
|
911
|
+
const includedMessages = transformRows(rows2.data);
|
|
912
|
+
const seen = /* @__PURE__ */ new Set();
|
|
913
|
+
const dedupedMessages = includedMessages.filter((message) => {
|
|
914
|
+
if (seen.has(message.id)) return false;
|
|
915
|
+
seen.add(message.id);
|
|
916
|
+
return true;
|
|
917
|
+
});
|
|
918
|
+
messages.push(...dedupedMessages);
|
|
919
|
+
}
|
|
920
|
+
let countQuery = `SELECT count() as total FROM ${storage.TABLE_MESSAGES} WHERE thread_id = {threadId:String}`;
|
|
921
|
+
const countParams = { threadId };
|
|
922
|
+
if (fromDate) {
|
|
923
|
+
countQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
|
|
924
|
+
countParams.fromDate = fromDate.toISOString();
|
|
925
|
+
}
|
|
926
|
+
if (toDate) {
|
|
927
|
+
countQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
|
|
928
|
+
countParams.toDate = toDate.toISOString();
|
|
929
|
+
}
|
|
930
|
+
const countResult = await this.client.query({
|
|
931
|
+
query: countQuery,
|
|
932
|
+
query_params: countParams,
|
|
933
|
+
clickhouse_settings: {
|
|
934
|
+
date_time_input_format: "best_effort",
|
|
935
|
+
date_time_output_format: "iso",
|
|
936
|
+
use_client_time_zone: 1,
|
|
937
|
+
output_format_json_quote_64bit_integers: 0
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
const countData = await countResult.json();
|
|
941
|
+
const total = countData.data[0].total;
|
|
942
|
+
if (total === 0 && messages.length === 0) {
|
|
943
|
+
return {
|
|
944
|
+
messages: [],
|
|
945
|
+
total: 0,
|
|
946
|
+
page,
|
|
947
|
+
perPage,
|
|
948
|
+
hasMore: false
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
const excludeIds = messages.map((m) => m.id);
|
|
952
|
+
let dataQuery = `
|
|
953
|
+
SELECT
|
|
954
|
+
id,
|
|
955
|
+
content,
|
|
956
|
+
role,
|
|
957
|
+
type,
|
|
958
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
959
|
+
thread_id AS "threadId",
|
|
960
|
+
resourceId
|
|
961
|
+
FROM ${storage.TABLE_MESSAGES}
|
|
962
|
+
WHERE thread_id = {threadId:String}
|
|
963
|
+
`;
|
|
964
|
+
const dataParams = { threadId };
|
|
965
|
+
if (fromDate) {
|
|
966
|
+
dataQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
|
|
967
|
+
dataParams.fromDate = fromDate.toISOString();
|
|
968
|
+
}
|
|
969
|
+
if (toDate) {
|
|
970
|
+
dataQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
|
|
971
|
+
dataParams.toDate = toDate.toISOString();
|
|
972
|
+
}
|
|
973
|
+
if (excludeIds.length > 0) {
|
|
974
|
+
dataQuery += ` AND id NOT IN ({excludeIds:Array(String)})`;
|
|
975
|
+
dataParams.excludeIds = excludeIds;
|
|
976
|
+
}
|
|
977
|
+
if (selectBy?.last) {
|
|
978
|
+
dataQuery += `
|
|
979
|
+
ORDER BY createdAt DESC
|
|
980
|
+
LIMIT {limit:Int64}
|
|
981
|
+
`;
|
|
982
|
+
dataParams.limit = perPage;
|
|
983
|
+
} else {
|
|
984
|
+
dataQuery += `
|
|
985
|
+
ORDER BY createdAt ASC
|
|
986
|
+
LIMIT {limit:Int64} OFFSET {offset:Int64}
|
|
987
|
+
`;
|
|
988
|
+
dataParams.limit = perPage;
|
|
989
|
+
dataParams.offset = offset;
|
|
990
|
+
}
|
|
991
|
+
const result = await this.client.query({
|
|
992
|
+
query: dataQuery,
|
|
993
|
+
query_params: dataParams,
|
|
994
|
+
clickhouse_settings: {
|
|
995
|
+
date_time_input_format: "best_effort",
|
|
996
|
+
date_time_output_format: "iso",
|
|
997
|
+
use_client_time_zone: 1,
|
|
998
|
+
output_format_json_quote_64bit_integers: 0
|
|
999
|
+
}
|
|
1000
|
+
});
|
|
1001
|
+
const rows = await result.json();
|
|
1002
|
+
const paginatedMessages = transformRows(rows.data);
|
|
1003
|
+
messages.push(...paginatedMessages);
|
|
1004
|
+
if (selectBy?.last) {
|
|
1005
|
+
messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
1006
|
+
}
|
|
1007
|
+
return {
|
|
1008
|
+
messages: format === "v2" ? messages : messages,
|
|
1009
|
+
total,
|
|
1010
|
+
page,
|
|
1011
|
+
perPage,
|
|
1012
|
+
hasMore: offset + perPage < total
|
|
1013
|
+
};
|
|
1014
|
+
} catch (error$1) {
|
|
1015
|
+
throw new error.MastraError(
|
|
1016
|
+
{
|
|
1017
|
+
id: "CLICKHOUSE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
|
|
1018
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1019
|
+
category: error.ErrorCategory.THIRD_PARTY
|
|
1020
|
+
},
|
|
1021
|
+
error$1
|
|
1022
|
+
);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
async updateMessages(args) {
|
|
1026
|
+
const { messages } = args;
|
|
1027
|
+
if (messages.length === 0) {
|
|
1028
|
+
return [];
|
|
1029
|
+
}
|
|
1030
|
+
try {
|
|
1031
|
+
const messageIds = messages.map((m) => m.id);
|
|
1032
|
+
const existingResult = await this.client.query({
|
|
1033
|
+
query: `SELECT id, content, role, type, "createdAt", thread_id AS "threadId", "resourceId" FROM ${storage.TABLE_MESSAGES} WHERE id IN (${messageIds.map((_, i) => `{id_${i}:String}`).join(",")})`,
|
|
1034
|
+
query_params: messageIds.reduce((acc, m, i) => ({ ...acc, [`id_${i}`]: m }), {}),
|
|
1035
|
+
clickhouse_settings: {
|
|
1036
|
+
date_time_input_format: "best_effort",
|
|
1037
|
+
date_time_output_format: "iso",
|
|
1038
|
+
use_client_time_zone: 1,
|
|
1039
|
+
output_format_json_quote_64bit_integers: 0
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
const existingRows = await existingResult.json();
|
|
1043
|
+
const existingMessages = transformRows(existingRows.data);
|
|
1044
|
+
if (existingMessages.length === 0) {
|
|
1045
|
+
return [];
|
|
1046
|
+
}
|
|
1047
|
+
const parsedExistingMessages = existingMessages.map((msg) => {
|
|
1048
|
+
if (typeof msg.content === "string") {
|
|
1049
|
+
try {
|
|
1050
|
+
msg.content = JSON.parse(msg.content);
|
|
1051
|
+
} catch {
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
return msg;
|
|
1055
|
+
});
|
|
1056
|
+
const threadIdsToUpdate = /* @__PURE__ */ new Set();
|
|
1057
|
+
const updatePromises = [];
|
|
1058
|
+
for (const existingMessage of parsedExistingMessages) {
|
|
1059
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1060
|
+
if (!updatePayload) continue;
|
|
1061
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1062
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1063
|
+
threadIdsToUpdate.add(existingMessage.threadId);
|
|
1064
|
+
if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
|
|
1065
|
+
threadIdsToUpdate.add(updatePayload.threadId);
|
|
1066
|
+
}
|
|
1067
|
+
const setClauses = [];
|
|
1068
|
+
const values = {};
|
|
1069
|
+
let paramIdx = 1;
|
|
1070
|
+
let newContent = null;
|
|
1071
|
+
const updatableFields = { ...fieldsToUpdate };
|
|
1072
|
+
if (updatableFields.content) {
|
|
1073
|
+
const existingContent = existingMessage.content || {};
|
|
1074
|
+
const existingMetadata = existingContent.metadata || {};
|
|
1075
|
+
const updateMetadata = updatableFields.content.metadata || {};
|
|
1076
|
+
newContent = {
|
|
1077
|
+
...existingContent,
|
|
1078
|
+
...updatableFields.content,
|
|
1079
|
+
// Deep merge metadata
|
|
1080
|
+
metadata: {
|
|
1081
|
+
...existingMetadata,
|
|
1082
|
+
...updateMetadata
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
setClauses.push(`content = {var_content_${paramIdx}:String}`);
|
|
1086
|
+
values[`var_content_${paramIdx}`] = JSON.stringify(newContent);
|
|
1087
|
+
paramIdx++;
|
|
1088
|
+
delete updatableFields.content;
|
|
1089
|
+
}
|
|
1090
|
+
for (const key in updatableFields) {
|
|
1091
|
+
if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
|
|
1092
|
+
const dbColumn = key === "threadId" ? "thread_id" : key;
|
|
1093
|
+
setClauses.push(`"${dbColumn}" = {var_${key}_${paramIdx}:String}`);
|
|
1094
|
+
values[`var_${key}_${paramIdx}`] = updatableFields[key];
|
|
1095
|
+
paramIdx++;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
if (setClauses.length > 0) {
|
|
1099
|
+
values[`var_id_${paramIdx}`] = id;
|
|
1100
|
+
const updateQuery = `
|
|
1101
|
+
ALTER TABLE ${storage.TABLE_MESSAGES}
|
|
1102
|
+
UPDATE ${setClauses.join(", ")}
|
|
1103
|
+
WHERE id = {var_id_${paramIdx}:String}
|
|
1104
|
+
`;
|
|
1105
|
+
console.log("Updating message:", id, "with query:", updateQuery, "values:", values);
|
|
1106
|
+
updatePromises.push(
|
|
1107
|
+
this.client.command({
|
|
1108
|
+
query: updateQuery,
|
|
1109
|
+
query_params: values,
|
|
1110
|
+
clickhouse_settings: {
|
|
1111
|
+
date_time_input_format: "best_effort",
|
|
1112
|
+
use_client_time_zone: 1,
|
|
1113
|
+
output_format_json_quote_64bit_integers: 0
|
|
1114
|
+
}
|
|
1115
|
+
})
|
|
1116
|
+
);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
if (updatePromises.length > 0) {
|
|
1120
|
+
await Promise.all(updatePromises);
|
|
1121
|
+
}
|
|
1122
|
+
await this.client.command({
|
|
1123
|
+
query: `OPTIMIZE TABLE ${storage.TABLE_MESSAGES} FINAL`,
|
|
1124
|
+
clickhouse_settings: {
|
|
1125
|
+
date_time_input_format: "best_effort",
|
|
1126
|
+
use_client_time_zone: 1,
|
|
1127
|
+
output_format_json_quote_64bit_integers: 0
|
|
1128
|
+
}
|
|
1129
|
+
});
|
|
1130
|
+
for (const existingMessage of parsedExistingMessages) {
|
|
1131
|
+
const updatePayload = messages.find((m) => m.id === existingMessage.id);
|
|
1132
|
+
if (!updatePayload) continue;
|
|
1133
|
+
const { id, ...fieldsToUpdate } = updatePayload;
|
|
1134
|
+
if (Object.keys(fieldsToUpdate).length === 0) continue;
|
|
1135
|
+
const verifyResult = await this.client.query({
|
|
1136
|
+
query: `SELECT id, content, role, type, "createdAt", thread_id AS "threadId", "resourceId" FROM ${storage.TABLE_MESSAGES} WHERE id = {messageId:String}`,
|
|
1137
|
+
query_params: { messageId: id },
|
|
1138
|
+
clickhouse_settings: {
|
|
1139
|
+
date_time_input_format: "best_effort",
|
|
1140
|
+
date_time_output_format: "iso",
|
|
1141
|
+
use_client_time_zone: 1,
|
|
1142
|
+
output_format_json_quote_64bit_integers: 0
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
const verifyRows = await verifyResult.json();
|
|
1146
|
+
if (verifyRows.data.length > 0) {
|
|
1147
|
+
const updatedMessage = transformRows(verifyRows.data)[0];
|
|
1148
|
+
if (updatedMessage) {
|
|
1149
|
+
let needsRetry = false;
|
|
1150
|
+
for (const [key, value] of Object.entries(fieldsToUpdate)) {
|
|
1151
|
+
if (key === "content") {
|
|
1152
|
+
const expectedContent = typeof value === "string" ? value : JSON.stringify(value);
|
|
1153
|
+
const actualContent = typeof updatedMessage.content === "string" ? updatedMessage.content : JSON.stringify(updatedMessage.content);
|
|
1154
|
+
if (actualContent !== expectedContent) {
|
|
1155
|
+
needsRetry = true;
|
|
1156
|
+
break;
|
|
1157
|
+
}
|
|
1158
|
+
} else if (updatedMessage[key] !== value) {
|
|
1159
|
+
needsRetry = true;
|
|
1160
|
+
break;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
if (needsRetry) {
|
|
1164
|
+
console.log("Update not applied correctly, retrying with DELETE + INSERT for message:", id);
|
|
1165
|
+
await this.client.command({
|
|
1166
|
+
query: `DELETE FROM ${storage.TABLE_MESSAGES} WHERE id = {messageId:String}`,
|
|
1167
|
+
query_params: { messageId: id },
|
|
1168
|
+
clickhouse_settings: {
|
|
1169
|
+
date_time_input_format: "best_effort",
|
|
1170
|
+
use_client_time_zone: 1,
|
|
1171
|
+
output_format_json_quote_64bit_integers: 0
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
let updatedContent = existingMessage.content || {};
|
|
1175
|
+
if (fieldsToUpdate.content) {
|
|
1176
|
+
const existingContent = existingMessage.content || {};
|
|
1177
|
+
const existingMetadata = existingContent.metadata || {};
|
|
1178
|
+
const updateMetadata = fieldsToUpdate.content.metadata || {};
|
|
1179
|
+
updatedContent = {
|
|
1180
|
+
...existingContent,
|
|
1181
|
+
...fieldsToUpdate.content,
|
|
1182
|
+
metadata: {
|
|
1183
|
+
...existingMetadata,
|
|
1184
|
+
...updateMetadata
|
|
1185
|
+
}
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
const updatedMessageData = {
|
|
1189
|
+
...existingMessage,
|
|
1190
|
+
...fieldsToUpdate,
|
|
1191
|
+
content: updatedContent
|
|
1192
|
+
};
|
|
1193
|
+
await this.client.insert({
|
|
1194
|
+
table: storage.TABLE_MESSAGES,
|
|
1195
|
+
format: "JSONEachRow",
|
|
1196
|
+
values: [
|
|
1197
|
+
{
|
|
1198
|
+
id: updatedMessageData.id,
|
|
1199
|
+
thread_id: updatedMessageData.threadId,
|
|
1200
|
+
resourceId: updatedMessageData.resourceId,
|
|
1201
|
+
content: typeof updatedMessageData.content === "string" ? updatedMessageData.content : JSON.stringify(updatedMessageData.content),
|
|
1202
|
+
createdAt: updatedMessageData.createdAt.toISOString(),
|
|
1203
|
+
role: updatedMessageData.role,
|
|
1204
|
+
type: updatedMessageData.type || "v2"
|
|
1205
|
+
}
|
|
1206
|
+
],
|
|
1207
|
+
clickhouse_settings: {
|
|
1208
|
+
date_time_input_format: "best_effort",
|
|
1209
|
+
use_client_time_zone: 1,
|
|
1210
|
+
output_format_json_quote_64bit_integers: 0
|
|
1211
|
+
}
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (threadIdsToUpdate.size > 0) {
|
|
1218
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
1219
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().replace("Z", "");
|
|
1220
|
+
const threadUpdatePromises = Array.from(threadIdsToUpdate).map(async (threadId) => {
|
|
1221
|
+
const threadResult = await this.client.query({
|
|
1222
|
+
query: `SELECT id, resourceId, title, metadata, createdAt FROM ${storage.TABLE_THREADS} WHERE id = {threadId:String}`,
|
|
1223
|
+
query_params: { threadId },
|
|
1224
|
+
clickhouse_settings: {
|
|
1225
|
+
date_time_input_format: "best_effort",
|
|
1226
|
+
date_time_output_format: "iso",
|
|
1227
|
+
use_client_time_zone: 1,
|
|
1228
|
+
output_format_json_quote_64bit_integers: 0
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
const threadRows = await threadResult.json();
|
|
1232
|
+
if (threadRows.data.length > 0) {
|
|
1233
|
+
const existingThread = threadRows.data[0];
|
|
1234
|
+
await this.client.command({
|
|
1235
|
+
query: `DELETE FROM ${storage.TABLE_THREADS} WHERE id = {threadId:String}`,
|
|
1236
|
+
query_params: { threadId },
|
|
1237
|
+
clickhouse_settings: {
|
|
1238
|
+
date_time_input_format: "best_effort",
|
|
1239
|
+
use_client_time_zone: 1,
|
|
1240
|
+
output_format_json_quote_64bit_integers: 0
|
|
1241
|
+
}
|
|
1242
|
+
});
|
|
1243
|
+
await this.client.insert({
|
|
1244
|
+
table: storage.TABLE_THREADS,
|
|
1245
|
+
format: "JSONEachRow",
|
|
1246
|
+
values: [
|
|
1247
|
+
{
|
|
1248
|
+
id: existingThread.id,
|
|
1249
|
+
resourceId: existingThread.resourceId,
|
|
1250
|
+
title: existingThread.title,
|
|
1251
|
+
metadata: existingThread.metadata,
|
|
1252
|
+
createdAt: existingThread.createdAt,
|
|
1253
|
+
updatedAt: now
|
|
1254
|
+
}
|
|
1255
|
+
],
|
|
1256
|
+
clickhouse_settings: {
|
|
1257
|
+
date_time_input_format: "best_effort",
|
|
1258
|
+
use_client_time_zone: 1,
|
|
1259
|
+
output_format_json_quote_64bit_integers: 0
|
|
1260
|
+
}
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
});
|
|
1264
|
+
await Promise.all(threadUpdatePromises);
|
|
1265
|
+
}
|
|
1266
|
+
const updatedMessages = [];
|
|
1267
|
+
for (const messageId of messageIds) {
|
|
1268
|
+
const updatedResult = await this.client.query({
|
|
1269
|
+
query: `SELECT id, content, role, type, "createdAt", thread_id AS "threadId", "resourceId" FROM ${storage.TABLE_MESSAGES} WHERE id = {messageId:String}`,
|
|
1270
|
+
query_params: { messageId },
|
|
1271
|
+
clickhouse_settings: {
|
|
1272
|
+
date_time_input_format: "best_effort",
|
|
1273
|
+
date_time_output_format: "iso",
|
|
1274
|
+
use_client_time_zone: 1,
|
|
1275
|
+
output_format_json_quote_64bit_integers: 0
|
|
1276
|
+
}
|
|
1277
|
+
});
|
|
1278
|
+
const updatedRows = await updatedResult.json();
|
|
1279
|
+
if (updatedRows.data.length > 0) {
|
|
1280
|
+
const message = transformRows(updatedRows.data)[0];
|
|
1281
|
+
if (message) {
|
|
1282
|
+
updatedMessages.push(message);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
return updatedMessages.map((message) => {
|
|
1287
|
+
if (typeof message.content === "string") {
|
|
1288
|
+
try {
|
|
1289
|
+
message.content = JSON.parse(message.content);
|
|
1290
|
+
} catch {
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
return message;
|
|
1294
|
+
});
|
|
1295
|
+
} catch (error$1) {
|
|
1296
|
+
throw new error.MastraError(
|
|
1297
|
+
{
|
|
1298
|
+
id: "CLICKHOUSE_STORAGE_UPDATE_MESSAGES_FAILED",
|
|
1299
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1300
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1301
|
+
details: { messageIds: messages.map((m) => m.id).join(",") }
|
|
1302
|
+
},
|
|
1303
|
+
error$1
|
|
1304
|
+
);
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
async getResourceById({ resourceId }) {
|
|
1308
|
+
try {
|
|
1309
|
+
const result = await this.client.query({
|
|
1310
|
+
query: `SELECT id, workingMemory, metadata, createdAt, updatedAt FROM ${storage.TABLE_RESOURCES} WHERE id = {resourceId:String}`,
|
|
1311
|
+
query_params: { resourceId },
|
|
1312
|
+
clickhouse_settings: {
|
|
1313
|
+
date_time_input_format: "best_effort",
|
|
1314
|
+
date_time_output_format: "iso",
|
|
1315
|
+
use_client_time_zone: 1,
|
|
1316
|
+
output_format_json_quote_64bit_integers: 0
|
|
1317
|
+
}
|
|
1318
|
+
});
|
|
1319
|
+
const rows = await result.json();
|
|
1320
|
+
if (rows.data.length === 0) {
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
const resource = rows.data[0];
|
|
1324
|
+
return {
|
|
1325
|
+
id: resource.id,
|
|
1326
|
+
workingMemory: resource.workingMemory && typeof resource.workingMemory === "object" ? JSON.stringify(resource.workingMemory) : resource.workingMemory,
|
|
1327
|
+
metadata: resource.metadata && typeof resource.metadata === "string" ? JSON.parse(resource.metadata) : resource.metadata,
|
|
1328
|
+
createdAt: new Date(resource.createdAt),
|
|
1329
|
+
updatedAt: new Date(resource.updatedAt)
|
|
1330
|
+
};
|
|
1331
|
+
} catch (error$1) {
|
|
1332
|
+
throw new error.MastraError(
|
|
1333
|
+
{
|
|
1334
|
+
id: "CLICKHOUSE_STORAGE_GET_RESOURCE_BY_ID_FAILED",
|
|
1335
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1336
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1337
|
+
details: { resourceId }
|
|
1338
|
+
},
|
|
1339
|
+
error$1
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
async saveResource({ resource }) {
|
|
1344
|
+
try {
|
|
1345
|
+
await this.client.insert({
|
|
1346
|
+
table: storage.TABLE_RESOURCES,
|
|
1347
|
+
format: "JSONEachRow",
|
|
1348
|
+
values: [
|
|
1349
|
+
{
|
|
1350
|
+
id: resource.id,
|
|
1351
|
+
workingMemory: resource.workingMemory,
|
|
1352
|
+
metadata: JSON.stringify(resource.metadata),
|
|
1353
|
+
createdAt: resource.createdAt.toISOString(),
|
|
1354
|
+
updatedAt: resource.updatedAt.toISOString()
|
|
1355
|
+
}
|
|
1356
|
+
],
|
|
1357
|
+
clickhouse_settings: {
|
|
1358
|
+
date_time_input_format: "best_effort",
|
|
1359
|
+
use_client_time_zone: 1,
|
|
1360
|
+
output_format_json_quote_64bit_integers: 0
|
|
1361
|
+
}
|
|
1362
|
+
});
|
|
1363
|
+
return resource;
|
|
1364
|
+
} catch (error$1) {
|
|
1365
|
+
throw new error.MastraError(
|
|
1366
|
+
{
|
|
1367
|
+
id: "CLICKHOUSE_STORAGE_SAVE_RESOURCE_FAILED",
|
|
1368
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1369
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1370
|
+
details: { resourceId: resource.id }
|
|
1371
|
+
},
|
|
1372
|
+
error$1
|
|
1373
|
+
);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
async updateResource({
|
|
1377
|
+
resourceId,
|
|
1378
|
+
workingMemory,
|
|
1379
|
+
metadata
|
|
1380
|
+
}) {
|
|
1381
|
+
try {
|
|
1382
|
+
const existingResource = await this.getResourceById({ resourceId });
|
|
1383
|
+
if (!existingResource) {
|
|
1384
|
+
const newResource = {
|
|
1385
|
+
id: resourceId,
|
|
1386
|
+
workingMemory,
|
|
1387
|
+
metadata: metadata || {},
|
|
1388
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1389
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1390
|
+
};
|
|
1391
|
+
return this.saveResource({ resource: newResource });
|
|
1392
|
+
}
|
|
1393
|
+
const updatedResource = {
|
|
1394
|
+
...existingResource,
|
|
1395
|
+
workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
|
|
1396
|
+
metadata: {
|
|
1397
|
+
...existingResource.metadata,
|
|
1398
|
+
...metadata
|
|
1399
|
+
},
|
|
1400
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1401
|
+
};
|
|
1402
|
+
const updateQuery = `
|
|
1403
|
+
ALTER TABLE ${storage.TABLE_RESOURCES}
|
|
1404
|
+
UPDATE workingMemory = {workingMemory:String}, metadata = {metadata:String}, updatedAt = {updatedAt:String}
|
|
1405
|
+
WHERE id = {resourceId:String}
|
|
1406
|
+
`;
|
|
1407
|
+
await this.client.command({
|
|
1408
|
+
query: updateQuery,
|
|
1409
|
+
query_params: {
|
|
1410
|
+
workingMemory: updatedResource.workingMemory,
|
|
1411
|
+
metadata: JSON.stringify(updatedResource.metadata),
|
|
1412
|
+
updatedAt: updatedResource.updatedAt.toISOString().replace("Z", ""),
|
|
1413
|
+
resourceId
|
|
1414
|
+
},
|
|
1415
|
+
clickhouse_settings: {
|
|
1416
|
+
date_time_input_format: "best_effort",
|
|
1417
|
+
use_client_time_zone: 1,
|
|
1418
|
+
output_format_json_quote_64bit_integers: 0
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
await this.client.command({
|
|
1422
|
+
query: `OPTIMIZE TABLE ${storage.TABLE_RESOURCES} FINAL`,
|
|
1423
|
+
clickhouse_settings: {
|
|
1424
|
+
date_time_input_format: "best_effort",
|
|
1425
|
+
use_client_time_zone: 1,
|
|
1426
|
+
output_format_json_quote_64bit_integers: 0
|
|
1427
|
+
}
|
|
1428
|
+
});
|
|
1429
|
+
return updatedResource;
|
|
1430
|
+
} catch (error$1) {
|
|
1431
|
+
throw new error.MastraError(
|
|
1432
|
+
{
|
|
1433
|
+
id: "CLICKHOUSE_STORAGE_UPDATE_RESOURCE_FAILED",
|
|
1434
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1435
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1436
|
+
details: { resourceId }
|
|
1437
|
+
},
|
|
1438
|
+
error$1
|
|
1439
|
+
);
|
|
193
1440
|
}
|
|
194
|
-
const resp = await result.json();
|
|
195
|
-
const rows = resp.data;
|
|
196
|
-
return rows.map((row) => ({
|
|
197
|
-
id: row.id,
|
|
198
|
-
parentSpanId: row.parentSpanId,
|
|
199
|
-
traceId: row.traceId,
|
|
200
|
-
name: row.name,
|
|
201
|
-
scope: row.scope,
|
|
202
|
-
kind: row.kind,
|
|
203
|
-
status: safelyParseJSON(row.status),
|
|
204
|
-
events: safelyParseJSON(row.events),
|
|
205
|
-
links: safelyParseJSON(row.links),
|
|
206
|
-
attributes: safelyParseJSON(row.attributes),
|
|
207
|
-
startTime: row.startTime,
|
|
208
|
-
endTime: row.endTime,
|
|
209
|
-
other: safelyParseJSON(row.other),
|
|
210
|
-
createdAt: row.createdAt
|
|
211
|
-
}));
|
|
212
1441
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
1442
|
+
};
|
|
1443
|
+
var StoreOperationsClickhouse = class extends storage.StoreOperations {
|
|
1444
|
+
ttl;
|
|
1445
|
+
client;
|
|
1446
|
+
constructor({ client, ttl }) {
|
|
1447
|
+
super();
|
|
1448
|
+
this.ttl = ttl;
|
|
1449
|
+
this.client = client;
|
|
217
1450
|
}
|
|
218
|
-
async
|
|
219
|
-
await this.
|
|
220
|
-
query: `
|
|
1451
|
+
async hasColumn(table, column) {
|
|
1452
|
+
const result = await this.client.query({
|
|
1453
|
+
query: `DESCRIBE TABLE ${table}`,
|
|
1454
|
+
format: "JSONEachRow"
|
|
221
1455
|
});
|
|
1456
|
+
const columns = await result.json();
|
|
1457
|
+
return columns.some((c) => c.name === column);
|
|
1458
|
+
}
|
|
1459
|
+
getSqlType(type) {
|
|
1460
|
+
switch (type) {
|
|
1461
|
+
case "text":
|
|
1462
|
+
return "String";
|
|
1463
|
+
case "timestamp":
|
|
1464
|
+
return "DateTime64(3)";
|
|
1465
|
+
case "integer":
|
|
1466
|
+
case "bigint":
|
|
1467
|
+
return "Int64";
|
|
1468
|
+
case "jsonb":
|
|
1469
|
+
return "String";
|
|
1470
|
+
default:
|
|
1471
|
+
return super.getSqlType(type);
|
|
1472
|
+
}
|
|
222
1473
|
}
|
|
223
1474
|
async createTable({
|
|
224
1475
|
tableName,
|
|
@@ -233,25 +1484,25 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
233
1484
|
}).join(",\n");
|
|
234
1485
|
const rowTtl = this.ttl?.[tableName]?.row;
|
|
235
1486
|
const sql = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? `
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
await this.
|
|
1487
|
+
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
1488
|
+
${["id String"].concat(columns)}
|
|
1489
|
+
)
|
|
1490
|
+
ENGINE = ${TABLE_ENGINES[tableName] ?? "MergeTree()"}
|
|
1491
|
+
PRIMARY KEY (createdAt, run_id, workflow_name)
|
|
1492
|
+
ORDER BY (createdAt, run_id, workflow_name)
|
|
1493
|
+
${rowTtl ? `TTL toDateTime(${rowTtl.ttlKey ?? "createdAt"}) + INTERVAL ${rowTtl.interval} ${rowTtl.unit}` : ""}
|
|
1494
|
+
SETTINGS index_granularity = 8192
|
|
1495
|
+
` : `
|
|
1496
|
+
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
1497
|
+
${columns}
|
|
1498
|
+
)
|
|
1499
|
+
ENGINE = ${TABLE_ENGINES[tableName] ?? "MergeTree()"}
|
|
1500
|
+
PRIMARY KEY (createdAt, ${tableName === storage.TABLE_EVALS ? "run_id" : "id"})
|
|
1501
|
+
ORDER BY (createdAt, ${tableName === storage.TABLE_EVALS ? "run_id" : "id"})
|
|
1502
|
+
${this.ttl?.[tableName]?.row ? `TTL toDateTime(createdAt) + INTERVAL ${this.ttl[tableName].row.interval} ${this.ttl[tableName].row.unit}` : ""}
|
|
1503
|
+
SETTINGS index_granularity = 8192
|
|
1504
|
+
`;
|
|
1505
|
+
await this.client.query({
|
|
255
1506
|
query: sql,
|
|
256
1507
|
clickhouse_settings: {
|
|
257
1508
|
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
@@ -261,14 +1512,60 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
261
1512
|
output_format_json_quote_64bit_integers: 0
|
|
262
1513
|
}
|
|
263
1514
|
});
|
|
264
|
-
} catch (error) {
|
|
265
|
-
|
|
266
|
-
|
|
1515
|
+
} catch (error$1) {
|
|
1516
|
+
throw new error.MastraError(
|
|
1517
|
+
{
|
|
1518
|
+
id: "CLICKHOUSE_STORAGE_CREATE_TABLE_FAILED",
|
|
1519
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1520
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1521
|
+
details: { tableName }
|
|
1522
|
+
},
|
|
1523
|
+
error$1
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
async alterTable({
|
|
1528
|
+
tableName,
|
|
1529
|
+
schema,
|
|
1530
|
+
ifNotExists
|
|
1531
|
+
}) {
|
|
1532
|
+
try {
|
|
1533
|
+
const describeSql = `DESCRIBE TABLE ${tableName}`;
|
|
1534
|
+
const result = await this.client.query({
|
|
1535
|
+
query: describeSql
|
|
1536
|
+
});
|
|
1537
|
+
const rows = await result.json();
|
|
1538
|
+
const existingColumnNames = new Set(rows.data.map((row) => row.name.toLowerCase()));
|
|
1539
|
+
for (const columnName of ifNotExists) {
|
|
1540
|
+
if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
|
|
1541
|
+
const columnDef = schema[columnName];
|
|
1542
|
+
let sqlType = this.getSqlType(columnDef.type);
|
|
1543
|
+
if (columnDef.nullable !== false) {
|
|
1544
|
+
sqlType = `Nullable(${sqlType})`;
|
|
1545
|
+
}
|
|
1546
|
+
const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
|
|
1547
|
+
const alterSql = `ALTER TABLE ${tableName} ADD COLUMN IF NOT EXISTS "${columnName}" ${sqlType} ${defaultValue}`.trim();
|
|
1548
|
+
await this.client.query({
|
|
1549
|
+
query: alterSql
|
|
1550
|
+
});
|
|
1551
|
+
this.logger?.debug?.(`Added column ${columnName} to table ${tableName}`);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
} catch (error$1) {
|
|
1555
|
+
throw new error.MastraError(
|
|
1556
|
+
{
|
|
1557
|
+
id: "CLICKHOUSE_STORAGE_ALTER_TABLE_FAILED",
|
|
1558
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1559
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1560
|
+
details: { tableName }
|
|
1561
|
+
},
|
|
1562
|
+
error$1
|
|
1563
|
+
);
|
|
267
1564
|
}
|
|
268
1565
|
}
|
|
269
1566
|
async clearTable({ tableName }) {
|
|
270
1567
|
try {
|
|
271
|
-
await this.
|
|
1568
|
+
await this.client.query({
|
|
272
1569
|
query: `TRUNCATE TABLE ${tableName}`,
|
|
273
1570
|
clickhouse_settings: {
|
|
274
1571
|
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
@@ -278,20 +1575,34 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
278
1575
|
output_format_json_quote_64bit_integers: 0
|
|
279
1576
|
}
|
|
280
1577
|
});
|
|
281
|
-
} catch (error) {
|
|
282
|
-
|
|
283
|
-
|
|
1578
|
+
} catch (error$1) {
|
|
1579
|
+
throw new error.MastraError(
|
|
1580
|
+
{
|
|
1581
|
+
id: "CLICKHOUSE_STORAGE_CLEAR_TABLE_FAILED",
|
|
1582
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1583
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1584
|
+
details: { tableName }
|
|
1585
|
+
},
|
|
1586
|
+
error$1
|
|
1587
|
+
);
|
|
284
1588
|
}
|
|
285
1589
|
}
|
|
1590
|
+
async dropTable({ tableName }) {
|
|
1591
|
+
await this.client.query({
|
|
1592
|
+
query: `DROP TABLE IF EXISTS ${tableName}`
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
286
1595
|
async insert({ tableName, record }) {
|
|
1596
|
+
const createdAt = (record.createdAt || record.created_at || /* @__PURE__ */ new Date()).toISOString();
|
|
1597
|
+
const updatedAt = (record.updatedAt || /* @__PURE__ */ new Date()).toISOString();
|
|
287
1598
|
try {
|
|
288
|
-
await this.
|
|
1599
|
+
const result = await this.client.insert({
|
|
289
1600
|
table: tableName,
|
|
290
1601
|
values: [
|
|
291
1602
|
{
|
|
292
1603
|
...record,
|
|
293
|
-
createdAt
|
|
294
|
-
updatedAt
|
|
1604
|
+
createdAt,
|
|
1605
|
+
updatedAt
|
|
295
1606
|
}
|
|
296
1607
|
],
|
|
297
1608
|
format: "JSONEachRow",
|
|
@@ -302,13 +1613,55 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
302
1613
|
use_client_time_zone: 1
|
|
303
1614
|
}
|
|
304
1615
|
});
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
throw error
|
|
1616
|
+
console.log("INSERT RESULT", result);
|
|
1617
|
+
} catch (error$1) {
|
|
1618
|
+
throw new error.MastraError(
|
|
1619
|
+
{
|
|
1620
|
+
id: "CLICKHOUSE_STORAGE_INSERT_FAILED",
|
|
1621
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1622
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1623
|
+
details: { tableName }
|
|
1624
|
+
},
|
|
1625
|
+
error$1
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
async batchInsert({ tableName, records }) {
|
|
1630
|
+
const recordsToBeInserted = records.map((record) => ({
|
|
1631
|
+
...Object.fromEntries(
|
|
1632
|
+
Object.entries(record).map(([key, value]) => [
|
|
1633
|
+
key,
|
|
1634
|
+
storage.TABLE_SCHEMAS[tableName]?.[key]?.type === "timestamp" ? new Date(value).toISOString() : value
|
|
1635
|
+
])
|
|
1636
|
+
)
|
|
1637
|
+
}));
|
|
1638
|
+
try {
|
|
1639
|
+
await this.client.insert({
|
|
1640
|
+
table: tableName,
|
|
1641
|
+
values: recordsToBeInserted,
|
|
1642
|
+
format: "JSONEachRow",
|
|
1643
|
+
clickhouse_settings: {
|
|
1644
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
1645
|
+
date_time_input_format: "best_effort",
|
|
1646
|
+
use_client_time_zone: 1,
|
|
1647
|
+
output_format_json_quote_64bit_integers: 0
|
|
1648
|
+
}
|
|
1649
|
+
});
|
|
1650
|
+
} catch (error$1) {
|
|
1651
|
+
throw new error.MastraError(
|
|
1652
|
+
{
|
|
1653
|
+
id: "CLICKHOUSE_STORAGE_BATCH_INSERT_FAILED",
|
|
1654
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1655
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1656
|
+
details: { tableName }
|
|
1657
|
+
},
|
|
1658
|
+
error$1
|
|
1659
|
+
);
|
|
308
1660
|
}
|
|
309
1661
|
}
|
|
310
1662
|
async load({ tableName, keys }) {
|
|
311
1663
|
try {
|
|
1664
|
+
const engine = TABLE_ENGINES[tableName] ?? "MergeTree()";
|
|
312
1665
|
const keyEntries = Object.entries(keys);
|
|
313
1666
|
const conditions = keyEntries.map(
|
|
314
1667
|
([key]) => `"${key}" = {var_${key}:${COLUMN_TYPES[storage.TABLE_SCHEMAS[tableName]?.[key]?.type ?? "text"]}}`
|
|
@@ -316,8 +1669,10 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
316
1669
|
const values = keyEntries.reduce((acc, [key, value]) => {
|
|
317
1670
|
return { ...acc, [`var_${key}`]: value };
|
|
318
1671
|
}, {});
|
|
319
|
-
const
|
|
320
|
-
|
|
1672
|
+
const hasUpdatedAt = storage.TABLE_SCHEMAS[tableName]?.updatedAt;
|
|
1673
|
+
const selectClause = `SELECT *, toDateTime64(createdAt, 3) as createdAt${hasUpdatedAt ? ", toDateTime64(updatedAt, 3) as updatedAt" : ""}`;
|
|
1674
|
+
const result = await this.client.query({
|
|
1675
|
+
query: `${selectClause} FROM ${tableName} ${engine.startsWith("ReplacingMergeTree") ? "FINAL" : ""} WHERE ${conditions} ORDER BY createdAt DESC LIMIT 1`,
|
|
321
1676
|
query_params: values,
|
|
322
1677
|
clickhouse_settings: {
|
|
323
1678
|
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
@@ -343,25 +1698,58 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
343
1698
|
}
|
|
344
1699
|
const data = transformRow(rows.data[0]);
|
|
345
1700
|
return data;
|
|
346
|
-
} catch (error) {
|
|
347
|
-
|
|
348
|
-
|
|
1701
|
+
} catch (error$1) {
|
|
1702
|
+
throw new error.MastraError(
|
|
1703
|
+
{
|
|
1704
|
+
id: "CLICKHOUSE_STORAGE_LOAD_FAILED",
|
|
1705
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1706
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1707
|
+
details: { tableName }
|
|
1708
|
+
},
|
|
1709
|
+
error$1
|
|
1710
|
+
);
|
|
349
1711
|
}
|
|
350
1712
|
}
|
|
351
|
-
|
|
1713
|
+
};
|
|
1714
|
+
var ScoresStorageClickhouse = class extends storage.ScoresStorage {
|
|
1715
|
+
client;
|
|
1716
|
+
operations;
|
|
1717
|
+
constructor({ client, operations }) {
|
|
1718
|
+
super();
|
|
1719
|
+
this.client = client;
|
|
1720
|
+
this.operations = operations;
|
|
1721
|
+
}
|
|
1722
|
+
transformScoreRow(row) {
|
|
1723
|
+
const scorer = storage.safelyParseJSON(row.scorer);
|
|
1724
|
+
const preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
|
|
1725
|
+
const analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
|
|
1726
|
+
const metadata = storage.safelyParseJSON(row.metadata);
|
|
1727
|
+
const input = storage.safelyParseJSON(row.input);
|
|
1728
|
+
const output = storage.safelyParseJSON(row.output);
|
|
1729
|
+
const additionalContext = storage.safelyParseJSON(row.additionalContext);
|
|
1730
|
+
const runtimeContext = storage.safelyParseJSON(row.runtimeContext);
|
|
1731
|
+
const entity = storage.safelyParseJSON(row.entity);
|
|
1732
|
+
return {
|
|
1733
|
+
...row,
|
|
1734
|
+
scorer,
|
|
1735
|
+
preprocessStepResult,
|
|
1736
|
+
analyzeStepResult,
|
|
1737
|
+
metadata,
|
|
1738
|
+
input,
|
|
1739
|
+
output,
|
|
1740
|
+
additionalContext,
|
|
1741
|
+
runtimeContext,
|
|
1742
|
+
entity,
|
|
1743
|
+
createdAt: new Date(row.createdAt),
|
|
1744
|
+
updatedAt: new Date(row.updatedAt)
|
|
1745
|
+
};
|
|
1746
|
+
}
|
|
1747
|
+
async getScoreById({ id }) {
|
|
352
1748
|
try {
|
|
353
|
-
const result = await this.
|
|
354
|
-
query: `SELECT
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
title,
|
|
358
|
-
metadata,
|
|
359
|
-
toDateTime64(createdAt, 3) as createdAt,
|
|
360
|
-
toDateTime64(updatedAt, 3) as updatedAt
|
|
361
|
-
FROM "${storage.TABLE_THREADS}"
|
|
362
|
-
FINAL
|
|
363
|
-
WHERE id = {var_id:String}`,
|
|
364
|
-
query_params: { var_id: threadId },
|
|
1749
|
+
const result = await this.client.query({
|
|
1750
|
+
query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE id = {var_id:String}`,
|
|
1751
|
+
query_params: { var_id: id },
|
|
1752
|
+
format: "JSONEachRow",
|
|
365
1753
|
clickhouse_settings: {
|
|
366
1754
|
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
367
1755
|
date_time_input_format: "best_effort",
|
|
@@ -370,288 +1758,547 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
370
1758
|
output_format_json_quote_64bit_integers: 0
|
|
371
1759
|
}
|
|
372
1760
|
});
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
if (!thread) {
|
|
1761
|
+
const resultJson = await result.json();
|
|
1762
|
+
if (!Array.isArray(resultJson) || resultJson.length === 0) {
|
|
376
1763
|
return null;
|
|
377
1764
|
}
|
|
378
|
-
return
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
1765
|
+
return this.transformScoreRow(resultJson[0]);
|
|
1766
|
+
} catch (error$1) {
|
|
1767
|
+
throw new error.MastraError(
|
|
1768
|
+
{
|
|
1769
|
+
id: "CLICKHOUSE_STORAGE_GET_SCORE_BY_ID_FAILED",
|
|
1770
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1771
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1772
|
+
details: { scoreId: id }
|
|
1773
|
+
},
|
|
1774
|
+
error$1
|
|
1775
|
+
);
|
|
387
1776
|
}
|
|
388
1777
|
}
|
|
389
|
-
async
|
|
1778
|
+
async saveScore(score) {
|
|
390
1779
|
try {
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
toDateTime64(updatedAt, 3) as updatedAt
|
|
399
|
-
FROM "${storage.TABLE_THREADS}"
|
|
400
|
-
WHERE "resourceId" = {var_resourceId:String}`,
|
|
401
|
-
query_params: { var_resourceId: resourceId },
|
|
1780
|
+
const record = {
|
|
1781
|
+
...score
|
|
1782
|
+
};
|
|
1783
|
+
await this.client.insert({
|
|
1784
|
+
table: storage.TABLE_SCORERS,
|
|
1785
|
+
values: [record],
|
|
1786
|
+
format: "JSONEachRow",
|
|
402
1787
|
clickhouse_settings: {
|
|
403
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
404
1788
|
date_time_input_format: "best_effort",
|
|
405
|
-
date_time_output_format: "iso",
|
|
406
1789
|
use_client_time_zone: 1,
|
|
407
1790
|
output_format_json_quote_64bit_integers: 0
|
|
408
1791
|
}
|
|
409
1792
|
});
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
1793
|
+
return { score };
|
|
1794
|
+
} catch (error$1) {
|
|
1795
|
+
throw new error.MastraError(
|
|
1796
|
+
{
|
|
1797
|
+
id: "CLICKHOUSE_STORAGE_SAVE_SCORE_FAILED",
|
|
1798
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1799
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1800
|
+
details: { scoreId: score.id }
|
|
1801
|
+
},
|
|
1802
|
+
error$1
|
|
1803
|
+
);
|
|
421
1804
|
}
|
|
422
1805
|
}
|
|
423
|
-
async
|
|
1806
|
+
async getScoresByRunId({
|
|
1807
|
+
runId,
|
|
1808
|
+
pagination
|
|
1809
|
+
}) {
|
|
424
1810
|
try {
|
|
425
|
-
await this.
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
]
|
|
1811
|
+
const countResult = await this.client.query({
|
|
1812
|
+
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE runId = {var_runId:String}`,
|
|
1813
|
+
query_params: { var_runId: runId },
|
|
1814
|
+
format: "JSONEachRow"
|
|
1815
|
+
});
|
|
1816
|
+
const countRows = await countResult.json();
|
|
1817
|
+
let total = 0;
|
|
1818
|
+
if (Array.isArray(countRows) && countRows.length > 0 && countRows[0]) {
|
|
1819
|
+
const countObj = countRows[0];
|
|
1820
|
+
total = Number(countObj.count);
|
|
1821
|
+
}
|
|
1822
|
+
if (!total) {
|
|
1823
|
+
return {
|
|
1824
|
+
pagination: {
|
|
1825
|
+
total: 0,
|
|
1826
|
+
page: pagination.page,
|
|
1827
|
+
perPage: pagination.perPage,
|
|
1828
|
+
hasMore: false
|
|
1829
|
+
},
|
|
1830
|
+
scores: []
|
|
1831
|
+
};
|
|
1832
|
+
}
|
|
1833
|
+
const offset = pagination.page * pagination.perPage;
|
|
1834
|
+
const result = await this.client.query({
|
|
1835
|
+
query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE runId = {var_runId:String} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
|
|
1836
|
+
query_params: {
|
|
1837
|
+
var_runId: runId,
|
|
1838
|
+
var_limit: pagination.perPage,
|
|
1839
|
+
var_offset: offset
|
|
1840
|
+
},
|
|
434
1841
|
format: "JSONEachRow",
|
|
435
1842
|
clickhouse_settings: {
|
|
436
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
437
1843
|
date_time_input_format: "best_effort",
|
|
1844
|
+
date_time_output_format: "iso",
|
|
438
1845
|
use_client_time_zone: 1,
|
|
439
1846
|
output_format_json_quote_64bit_integers: 0
|
|
440
1847
|
}
|
|
441
1848
|
});
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
1849
|
+
const rows = await result.json();
|
|
1850
|
+
const scores = Array.isArray(rows) ? rows.map((row) => this.transformScoreRow(row)) : [];
|
|
1851
|
+
return {
|
|
1852
|
+
pagination: {
|
|
1853
|
+
total,
|
|
1854
|
+
page: pagination.page,
|
|
1855
|
+
perPage: pagination.perPage,
|
|
1856
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1857
|
+
},
|
|
1858
|
+
scores
|
|
1859
|
+
};
|
|
1860
|
+
} catch (error$1) {
|
|
1861
|
+
throw new error.MastraError(
|
|
1862
|
+
{
|
|
1863
|
+
id: "CLICKHOUSE_STORAGE_GET_SCORES_BY_RUN_ID_FAILED",
|
|
1864
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1865
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1866
|
+
details: { runId }
|
|
1867
|
+
},
|
|
1868
|
+
error$1
|
|
1869
|
+
);
|
|
446
1870
|
}
|
|
447
1871
|
}
|
|
448
|
-
async
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
1872
|
+
async getScoresByScorerId({
|
|
1873
|
+
scorerId,
|
|
1874
|
+
entityId,
|
|
1875
|
+
entityType,
|
|
1876
|
+
source,
|
|
1877
|
+
pagination
|
|
452
1878
|
}) {
|
|
1879
|
+
let whereClause = `scorerId = {var_scorerId:String}`;
|
|
1880
|
+
if (entityId) {
|
|
1881
|
+
whereClause += ` AND entityId = {var_entityId:String}`;
|
|
1882
|
+
}
|
|
1883
|
+
if (entityType) {
|
|
1884
|
+
whereClause += ` AND entityType = {var_entityType:String}`;
|
|
1885
|
+
}
|
|
1886
|
+
if (source) {
|
|
1887
|
+
whereClause += ` AND source = {var_source:String}`;
|
|
1888
|
+
}
|
|
453
1889
|
try {
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
1890
|
+
const countResult = await this.client.query({
|
|
1891
|
+
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE ${whereClause}`,
|
|
1892
|
+
query_params: {
|
|
1893
|
+
var_scorerId: scorerId,
|
|
1894
|
+
var_entityId: entityId,
|
|
1895
|
+
var_entityType: entityType,
|
|
1896
|
+
var_source: source
|
|
1897
|
+
},
|
|
1898
|
+
format: "JSONEachRow"
|
|
1899
|
+
});
|
|
1900
|
+
const countRows = await countResult.json();
|
|
1901
|
+
let total = 0;
|
|
1902
|
+
if (Array.isArray(countRows) && countRows.length > 0 && countRows[0]) {
|
|
1903
|
+
const countObj = countRows[0];
|
|
1904
|
+
total = Number(countObj.count);
|
|
457
1905
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1906
|
+
if (!total) {
|
|
1907
|
+
return {
|
|
1908
|
+
pagination: {
|
|
1909
|
+
total: 0,
|
|
1910
|
+
page: pagination.page,
|
|
1911
|
+
perPage: pagination.perPage,
|
|
1912
|
+
hasMore: false
|
|
1913
|
+
},
|
|
1914
|
+
scores: []
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1917
|
+
const offset = pagination.page * pagination.perPage;
|
|
1918
|
+
const result = await this.client.query({
|
|
1919
|
+
query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE ${whereClause} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
|
|
1920
|
+
query_params: {
|
|
1921
|
+
var_scorerId: scorerId,
|
|
1922
|
+
var_limit: pagination.perPage,
|
|
1923
|
+
var_offset: offset,
|
|
1924
|
+
var_entityId: entityId,
|
|
1925
|
+
var_entityType: entityType,
|
|
1926
|
+
var_source: source
|
|
1927
|
+
},
|
|
476
1928
|
format: "JSONEachRow",
|
|
477
1929
|
clickhouse_settings: {
|
|
478
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
479
1930
|
date_time_input_format: "best_effort",
|
|
1931
|
+
date_time_output_format: "iso",
|
|
480
1932
|
use_client_time_zone: 1,
|
|
481
1933
|
output_format_json_quote_64bit_integers: 0
|
|
482
1934
|
}
|
|
483
1935
|
});
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
1936
|
+
const rows = await result.json();
|
|
1937
|
+
const scores = Array.isArray(rows) ? rows.map((row) => this.transformScoreRow(row)) : [];
|
|
1938
|
+
return {
|
|
1939
|
+
pagination: {
|
|
1940
|
+
total,
|
|
1941
|
+
page: pagination.page,
|
|
1942
|
+
perPage: pagination.perPage,
|
|
1943
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
1944
|
+
},
|
|
1945
|
+
scores
|
|
1946
|
+
};
|
|
1947
|
+
} catch (error$1) {
|
|
1948
|
+
throw new error.MastraError(
|
|
1949
|
+
{
|
|
1950
|
+
id: "CLICKHOUSE_STORAGE_GET_SCORES_BY_SCORER_ID_FAILED",
|
|
1951
|
+
domain: error.ErrorDomain.STORAGE,
|
|
1952
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
1953
|
+
details: { scorerId }
|
|
1954
|
+
},
|
|
1955
|
+
error$1
|
|
1956
|
+
);
|
|
488
1957
|
}
|
|
489
1958
|
}
|
|
490
|
-
async
|
|
1959
|
+
async getScoresByEntityId({
|
|
1960
|
+
entityId,
|
|
1961
|
+
entityType,
|
|
1962
|
+
pagination
|
|
1963
|
+
}) {
|
|
491
1964
|
try {
|
|
492
|
-
await this.
|
|
493
|
-
query: `
|
|
494
|
-
query_params: {
|
|
495
|
-
|
|
496
|
-
output_format_json_quote_64bit_integers: 0
|
|
497
|
-
}
|
|
1965
|
+
const countResult = await this.client.query({
|
|
1966
|
+
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE entityId = {var_entityId:String} AND entityType = {var_entityType:String}`,
|
|
1967
|
+
query_params: { var_entityId: entityId, var_entityType: entityType },
|
|
1968
|
+
format: "JSONEachRow"
|
|
498
1969
|
});
|
|
499
|
-
await
|
|
500
|
-
|
|
501
|
-
|
|
1970
|
+
const countRows = await countResult.json();
|
|
1971
|
+
let total = 0;
|
|
1972
|
+
if (Array.isArray(countRows) && countRows.length > 0 && countRows[0]) {
|
|
1973
|
+
const countObj = countRows[0];
|
|
1974
|
+
total = Number(countObj.count);
|
|
1975
|
+
}
|
|
1976
|
+
if (!total) {
|
|
1977
|
+
return {
|
|
1978
|
+
pagination: {
|
|
1979
|
+
total: 0,
|
|
1980
|
+
page: pagination.page,
|
|
1981
|
+
perPage: pagination.perPage,
|
|
1982
|
+
hasMore: false
|
|
1983
|
+
},
|
|
1984
|
+
scores: []
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
const offset = pagination.page * pagination.perPage;
|
|
1988
|
+
const result = await this.client.query({
|
|
1989
|
+
query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE entityId = {var_entityId:String} AND entityType = {var_entityType:String} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
|
|
1990
|
+
query_params: {
|
|
1991
|
+
var_entityId: entityId,
|
|
1992
|
+
var_entityType: entityType,
|
|
1993
|
+
var_limit: pagination.perPage,
|
|
1994
|
+
var_offset: offset
|
|
1995
|
+
},
|
|
1996
|
+
format: "JSONEachRow",
|
|
502
1997
|
clickhouse_settings: {
|
|
1998
|
+
date_time_input_format: "best_effort",
|
|
1999
|
+
date_time_output_format: "iso",
|
|
2000
|
+
use_client_time_zone: 1,
|
|
503
2001
|
output_format_json_quote_64bit_integers: 0
|
|
504
2002
|
}
|
|
505
2003
|
});
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
ROW_NUMBER() OVER (ORDER BY "createdAt" DESC) as row_num
|
|
525
|
-
FROM "${storage.TABLE_MESSAGES}"
|
|
526
|
-
WHERE thread_id = {var_thread_id:String}
|
|
527
|
-
)
|
|
528
|
-
SELECT
|
|
529
|
-
m.id AS id,
|
|
530
|
-
m.content as content,
|
|
531
|
-
m.role as role,
|
|
532
|
-
m.type as type,
|
|
533
|
-
m.createdAt as createdAt,
|
|
534
|
-
m.updatedAt as updatedAt,
|
|
535
|
-
m.thread_id AS "threadId"
|
|
536
|
-
FROM ordered_messages m
|
|
537
|
-
WHERE m.id = ANY({var_include:Array(String)})
|
|
538
|
-
OR EXISTS (
|
|
539
|
-
SELECT 1 FROM ordered_messages target
|
|
540
|
-
WHERE target.id = ANY({var_include:Array(String)})
|
|
541
|
-
AND (
|
|
542
|
-
-- Get previous messages based on the max withPreviousMessages
|
|
543
|
-
(m.row_num <= target.row_num + {var_withPreviousMessages:Int64} AND m.row_num > target.row_num)
|
|
544
|
-
OR
|
|
545
|
-
-- Get next messages based on the max withNextMessages
|
|
546
|
-
(m.row_num >= target.row_num - {var_withNextMessages:Int64} AND m.row_num < target.row_num)
|
|
547
|
-
)
|
|
548
|
-
)
|
|
549
|
-
ORDER BY m."createdAt" DESC
|
|
550
|
-
`,
|
|
551
|
-
query_params: {
|
|
552
|
-
var_thread_id: threadId,
|
|
553
|
-
var_include: include.map((i) => i.id),
|
|
554
|
-
var_withPreviousMessages: Math.max(...include.map((i) => i.withPreviousMessages || 0)),
|
|
555
|
-
var_withNextMessages: Math.max(...include.map((i) => i.withNextMessages || 0))
|
|
556
|
-
},
|
|
557
|
-
clickhouse_settings: {
|
|
558
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
559
|
-
date_time_input_format: "best_effort",
|
|
560
|
-
date_time_output_format: "iso",
|
|
561
|
-
use_client_time_zone: 1,
|
|
562
|
-
output_format_json_quote_64bit_integers: 0
|
|
563
|
-
}
|
|
564
|
-
});
|
|
565
|
-
const rows2 = await includeResult.json();
|
|
566
|
-
messages.push(...transformRows(rows2.data));
|
|
567
|
-
}
|
|
568
|
-
const result = await this.db.query({
|
|
569
|
-
query: `
|
|
570
|
-
SELECT
|
|
571
|
-
id,
|
|
572
|
-
content,
|
|
573
|
-
role,
|
|
574
|
-
type,
|
|
575
|
-
toDateTime64(createdAt, 3) as createdAt,
|
|
576
|
-
thread_id AS "threadId"
|
|
577
|
-
FROM "${storage.TABLE_MESSAGES}"
|
|
578
|
-
WHERE thread_id = {threadId:String}
|
|
579
|
-
AND id NOT IN ({exclude:Array(String)})
|
|
580
|
-
ORDER BY "createdAt" DESC
|
|
581
|
-
LIMIT {limit:Int64}
|
|
582
|
-
`,
|
|
583
|
-
query_params: {
|
|
584
|
-
threadId,
|
|
585
|
-
exclude: messages.map((m) => m.id),
|
|
586
|
-
limit
|
|
2004
|
+
const rows = await result.json();
|
|
2005
|
+
const scores = Array.isArray(rows) ? rows.map((row) => this.transformScoreRow(row)) : [];
|
|
2006
|
+
return {
|
|
2007
|
+
pagination: {
|
|
2008
|
+
total,
|
|
2009
|
+
page: pagination.page,
|
|
2010
|
+
perPage: pagination.perPage,
|
|
2011
|
+
hasMore: total > (pagination.page + 1) * pagination.perPage
|
|
2012
|
+
},
|
|
2013
|
+
scores
|
|
2014
|
+
};
|
|
2015
|
+
} catch (error$1) {
|
|
2016
|
+
throw new error.MastraError(
|
|
2017
|
+
{
|
|
2018
|
+
id: "CLICKHOUSE_STORAGE_GET_SCORES_BY_ENTITY_ID_FAILED",
|
|
2019
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2020
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2021
|
+
details: { entityId, entityType }
|
|
587
2022
|
},
|
|
2023
|
+
error$1
|
|
2024
|
+
);
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
};
|
|
2028
|
+
var TracesStorageClickhouse = class extends storage.TracesStorage {
|
|
2029
|
+
client;
|
|
2030
|
+
operations;
|
|
2031
|
+
constructor({ client, operations }) {
|
|
2032
|
+
super();
|
|
2033
|
+
this.client = client;
|
|
2034
|
+
this.operations = operations;
|
|
2035
|
+
}
|
|
2036
|
+
async getTracesPaginated(args) {
|
|
2037
|
+
const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
|
|
2038
|
+
const fromDate = dateRange?.start;
|
|
2039
|
+
const toDate = dateRange?.end;
|
|
2040
|
+
const currentOffset = page * perPage;
|
|
2041
|
+
const queryArgs = {};
|
|
2042
|
+
const conditions = [];
|
|
2043
|
+
if (name) {
|
|
2044
|
+
conditions.push(`name LIKE CONCAT({var_name:String}, '%')`);
|
|
2045
|
+
queryArgs.var_name = name;
|
|
2046
|
+
}
|
|
2047
|
+
if (scope) {
|
|
2048
|
+
conditions.push(`scope = {var_scope:String}`);
|
|
2049
|
+
queryArgs.var_scope = scope;
|
|
2050
|
+
}
|
|
2051
|
+
if (attributes) {
|
|
2052
|
+
Object.entries(attributes).forEach(([key, value]) => {
|
|
2053
|
+
conditions.push(`JSONExtractString(attributes, '${key}') = {var_attr_${key}:String}`);
|
|
2054
|
+
queryArgs[`var_attr_${key}`] = value;
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
if (filters) {
|
|
2058
|
+
Object.entries(filters).forEach(([key, value]) => {
|
|
2059
|
+
conditions.push(`${key} = {var_col_${key}:${storage.TABLE_SCHEMAS.mastra_traces?.[key]?.type ?? "text"}}`);
|
|
2060
|
+
queryArgs[`var_col_${key}`] = value;
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
if (fromDate) {
|
|
2064
|
+
conditions.push(`createdAt >= parseDateTime64BestEffort({var_from_date:String})`);
|
|
2065
|
+
queryArgs.var_from_date = fromDate.toISOString();
|
|
2066
|
+
}
|
|
2067
|
+
if (toDate) {
|
|
2068
|
+
conditions.push(`createdAt <= parseDateTime64BestEffort({var_to_date:String})`);
|
|
2069
|
+
queryArgs.var_to_date = toDate.toISOString();
|
|
2070
|
+
}
|
|
2071
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
2072
|
+
try {
|
|
2073
|
+
const countResult = await this.client.query({
|
|
2074
|
+
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
|
|
2075
|
+
query_params: queryArgs,
|
|
588
2076
|
clickhouse_settings: {
|
|
589
|
-
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
590
2077
|
date_time_input_format: "best_effort",
|
|
591
2078
|
date_time_output_format: "iso",
|
|
592
2079
|
use_client_time_zone: 1,
|
|
593
2080
|
output_format_json_quote_64bit_integers: 0
|
|
594
2081
|
}
|
|
595
2082
|
});
|
|
596
|
-
const
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
2083
|
+
const countData = await countResult.json();
|
|
2084
|
+
const total = Number(countData.data?.[0]?.count ?? 0);
|
|
2085
|
+
if (total === 0) {
|
|
2086
|
+
return {
|
|
2087
|
+
traces: [],
|
|
2088
|
+
total: 0,
|
|
2089
|
+
page,
|
|
2090
|
+
perPage,
|
|
2091
|
+
hasMore: false
|
|
2092
|
+
};
|
|
2093
|
+
}
|
|
2094
|
+
const result = await this.client.query({
|
|
2095
|
+
query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT {var_limit:UInt32} OFFSET {var_offset:UInt32}`,
|
|
2096
|
+
query_params: { ...queryArgs, var_limit: perPage, var_offset: currentOffset },
|
|
2097
|
+
clickhouse_settings: {
|
|
2098
|
+
date_time_input_format: "best_effort",
|
|
2099
|
+
date_time_output_format: "iso",
|
|
2100
|
+
use_client_time_zone: 1,
|
|
2101
|
+
output_format_json_quote_64bit_integers: 0
|
|
605
2102
|
}
|
|
606
2103
|
});
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
2104
|
+
if (!result) {
|
|
2105
|
+
return {
|
|
2106
|
+
traces: [],
|
|
2107
|
+
total,
|
|
2108
|
+
page,
|
|
2109
|
+
perPage,
|
|
2110
|
+
hasMore: false
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
const resp = await result.json();
|
|
2114
|
+
const rows = resp.data;
|
|
2115
|
+
const traces = rows.map((row) => ({
|
|
2116
|
+
id: row.id,
|
|
2117
|
+
parentSpanId: row.parentSpanId,
|
|
2118
|
+
traceId: row.traceId,
|
|
2119
|
+
name: row.name,
|
|
2120
|
+
scope: row.scope,
|
|
2121
|
+
kind: row.kind,
|
|
2122
|
+
status: storage.safelyParseJSON(row.status),
|
|
2123
|
+
events: storage.safelyParseJSON(row.events),
|
|
2124
|
+
links: storage.safelyParseJSON(row.links),
|
|
2125
|
+
attributes: storage.safelyParseJSON(row.attributes),
|
|
2126
|
+
startTime: row.startTime,
|
|
2127
|
+
endTime: row.endTime,
|
|
2128
|
+
other: storage.safelyParseJSON(row.other),
|
|
2129
|
+
createdAt: row.createdAt
|
|
2130
|
+
}));
|
|
2131
|
+
return {
|
|
2132
|
+
traces,
|
|
2133
|
+
total,
|
|
2134
|
+
page,
|
|
2135
|
+
perPage,
|
|
2136
|
+
hasMore: currentOffset + traces.length < total
|
|
2137
|
+
};
|
|
2138
|
+
} catch (error$1) {
|
|
2139
|
+
if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
|
|
2140
|
+
return {
|
|
2141
|
+
traces: [],
|
|
2142
|
+
total: 0,
|
|
2143
|
+
page,
|
|
2144
|
+
perPage,
|
|
2145
|
+
hasMore: false
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
throw new error.MastraError(
|
|
2149
|
+
{
|
|
2150
|
+
id: "CLICKHOUSE_STORAGE_GET_TRACES_PAGINATED_FAILED",
|
|
2151
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2152
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2153
|
+
details: {
|
|
2154
|
+
name: name ?? null,
|
|
2155
|
+
scope: scope ?? null,
|
|
2156
|
+
page,
|
|
2157
|
+
perPage,
|
|
2158
|
+
attributes: attributes ? JSON.stringify(attributes) : null,
|
|
2159
|
+
filters: filters ? JSON.stringify(filters) : null,
|
|
2160
|
+
dateRange: dateRange ? JSON.stringify(dateRange) : null
|
|
2161
|
+
}
|
|
2162
|
+
},
|
|
2163
|
+
error$1
|
|
2164
|
+
);
|
|
611
2165
|
}
|
|
612
2166
|
}
|
|
613
|
-
async
|
|
614
|
-
|
|
2167
|
+
async getTraces({
|
|
2168
|
+
name,
|
|
2169
|
+
scope,
|
|
2170
|
+
page,
|
|
2171
|
+
perPage,
|
|
2172
|
+
attributes,
|
|
2173
|
+
filters,
|
|
2174
|
+
fromDate,
|
|
2175
|
+
toDate
|
|
2176
|
+
}) {
|
|
2177
|
+
const limit = perPage;
|
|
2178
|
+
const offset = page * perPage;
|
|
2179
|
+
const args = {};
|
|
2180
|
+
const conditions = [];
|
|
2181
|
+
if (name) {
|
|
2182
|
+
conditions.push(`name LIKE CONCAT({var_name:String}, '%')`);
|
|
2183
|
+
args.var_name = name;
|
|
2184
|
+
}
|
|
2185
|
+
if (scope) {
|
|
2186
|
+
conditions.push(`scope = {var_scope:String}`);
|
|
2187
|
+
args.var_scope = scope;
|
|
2188
|
+
}
|
|
2189
|
+
if (attributes) {
|
|
2190
|
+
Object.entries(attributes).forEach(([key, value]) => {
|
|
2191
|
+
conditions.push(`JSONExtractString(attributes, '${key}') = {var_attr_${key}:String}`);
|
|
2192
|
+
args[`var_attr_${key}`] = value;
|
|
2193
|
+
});
|
|
2194
|
+
}
|
|
2195
|
+
if (filters) {
|
|
2196
|
+
Object.entries(filters).forEach(([key, value]) => {
|
|
2197
|
+
conditions.push(`${key} = {var_col_${key}:${storage.TABLE_SCHEMAS.mastra_traces?.[key]?.type ?? "text"}}`);
|
|
2198
|
+
args[`var_col_${key}`] = value;
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
if (fromDate) {
|
|
2202
|
+
conditions.push(`createdAt >= {var_from_date:DateTime64(3)}`);
|
|
2203
|
+
args.var_from_date = fromDate.getTime() / 1e3;
|
|
2204
|
+
}
|
|
2205
|
+
if (toDate) {
|
|
2206
|
+
conditions.push(`createdAt <= {var_to_date:DateTime64(3)}`);
|
|
2207
|
+
args.var_to_date = toDate.getTime() / 1e3;
|
|
2208
|
+
}
|
|
2209
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
615
2210
|
try {
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
}
|
|
620
|
-
const thread = await this.getThreadById({ threadId });
|
|
621
|
-
if (!thread) {
|
|
622
|
-
throw new Error(`Thread ${threadId} not found`);
|
|
623
|
-
}
|
|
624
|
-
await this.db.insert({
|
|
625
|
-
table: storage.TABLE_MESSAGES,
|
|
626
|
-
format: "JSONEachRow",
|
|
627
|
-
values: messages.map((message) => ({
|
|
628
|
-
id: message.id,
|
|
629
|
-
thread_id: threadId,
|
|
630
|
-
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
631
|
-
createdAt: message.createdAt.toISOString(),
|
|
632
|
-
role: message.role,
|
|
633
|
-
type: message.type
|
|
634
|
-
})),
|
|
2211
|
+
const result = await this.client.query({
|
|
2212
|
+
query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
|
|
2213
|
+
query_params: args,
|
|
635
2214
|
clickhouse_settings: {
|
|
636
2215
|
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
637
2216
|
date_time_input_format: "best_effort",
|
|
2217
|
+
date_time_output_format: "iso",
|
|
638
2218
|
use_client_time_zone: 1,
|
|
639
2219
|
output_format_json_quote_64bit_integers: 0
|
|
640
2220
|
}
|
|
641
2221
|
});
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
2222
|
+
if (!result) {
|
|
2223
|
+
return [];
|
|
2224
|
+
}
|
|
2225
|
+
const resp = await result.json();
|
|
2226
|
+
const rows = resp.data;
|
|
2227
|
+
return rows.map((row) => ({
|
|
2228
|
+
id: row.id,
|
|
2229
|
+
parentSpanId: row.parentSpanId,
|
|
2230
|
+
traceId: row.traceId,
|
|
2231
|
+
name: row.name,
|
|
2232
|
+
scope: row.scope,
|
|
2233
|
+
kind: row.kind,
|
|
2234
|
+
status: storage.safelyParseJSON(row.status),
|
|
2235
|
+
events: storage.safelyParseJSON(row.events),
|
|
2236
|
+
links: storage.safelyParseJSON(row.links),
|
|
2237
|
+
attributes: storage.safelyParseJSON(row.attributes),
|
|
2238
|
+
startTime: row.startTime,
|
|
2239
|
+
endTime: row.endTime,
|
|
2240
|
+
other: storage.safelyParseJSON(row.other),
|
|
2241
|
+
createdAt: row.createdAt
|
|
2242
|
+
}));
|
|
2243
|
+
} catch (error$1) {
|
|
2244
|
+
if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
|
|
2245
|
+
return [];
|
|
2246
|
+
}
|
|
2247
|
+
throw new error.MastraError(
|
|
2248
|
+
{
|
|
2249
|
+
id: "CLICKHOUSE_STORAGE_GET_TRACES_FAILED",
|
|
2250
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2251
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2252
|
+
details: {
|
|
2253
|
+
name: name ?? null,
|
|
2254
|
+
scope: scope ?? null,
|
|
2255
|
+
page,
|
|
2256
|
+
perPage,
|
|
2257
|
+
attributes: attributes ? JSON.stringify(attributes) : null,
|
|
2258
|
+
filters: filters ? JSON.stringify(filters) : null,
|
|
2259
|
+
fromDate: fromDate?.toISOString() ?? null,
|
|
2260
|
+
toDate: toDate?.toISOString() ?? null
|
|
2261
|
+
}
|
|
2262
|
+
},
|
|
2263
|
+
error$1
|
|
2264
|
+
);
|
|
646
2265
|
}
|
|
647
2266
|
}
|
|
2267
|
+
async batchTraceInsert(args) {
|
|
2268
|
+
await this.operations.batchInsert({ tableName: storage.TABLE_TRACES, records: args.records });
|
|
2269
|
+
}
|
|
2270
|
+
};
|
|
2271
|
+
var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
|
|
2272
|
+
client;
|
|
2273
|
+
operations;
|
|
2274
|
+
constructor({ client, operations }) {
|
|
2275
|
+
super();
|
|
2276
|
+
this.operations = operations;
|
|
2277
|
+
this.client = client;
|
|
2278
|
+
}
|
|
2279
|
+
updateWorkflowResults({
|
|
2280
|
+
// workflowName,
|
|
2281
|
+
// runId,
|
|
2282
|
+
// stepId,
|
|
2283
|
+
// result,
|
|
2284
|
+
// runtimeContext,
|
|
2285
|
+
}) {
|
|
2286
|
+
throw new Error("Method not implemented.");
|
|
2287
|
+
}
|
|
2288
|
+
updateWorkflowState({
|
|
2289
|
+
// workflowName,
|
|
2290
|
+
// runId,
|
|
2291
|
+
// opts,
|
|
2292
|
+
}) {
|
|
2293
|
+
throw new Error("Method not implemented.");
|
|
2294
|
+
}
|
|
648
2295
|
async persistWorkflowSnapshot({
|
|
649
2296
|
workflowName,
|
|
650
2297
|
runId,
|
|
651
2298
|
snapshot
|
|
652
2299
|
}) {
|
|
653
2300
|
try {
|
|
654
|
-
const currentSnapshot = await this.load({
|
|
2301
|
+
const currentSnapshot = await this.operations.load({
|
|
655
2302
|
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
656
2303
|
keys: { workflow_name: workflowName, run_id: runId }
|
|
657
2304
|
});
|
|
@@ -667,7 +2314,7 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
667
2314
|
createdAt: now.toISOString(),
|
|
668
2315
|
updatedAt: now.toISOString()
|
|
669
2316
|
};
|
|
670
|
-
await this.
|
|
2317
|
+
await this.client.insert({
|
|
671
2318
|
table: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
672
2319
|
format: "JSONEachRow",
|
|
673
2320
|
values: [persisting],
|
|
@@ -678,9 +2325,16 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
678
2325
|
output_format_json_quote_64bit_integers: 0
|
|
679
2326
|
}
|
|
680
2327
|
});
|
|
681
|
-
} catch (error) {
|
|
682
|
-
|
|
683
|
-
|
|
2328
|
+
} catch (error$1) {
|
|
2329
|
+
throw new error.MastraError(
|
|
2330
|
+
{
|
|
2331
|
+
id: "CLICKHOUSE_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
|
|
2332
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2333
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2334
|
+
details: { workflowName, runId }
|
|
2335
|
+
},
|
|
2336
|
+
error$1
|
|
2337
|
+
);
|
|
684
2338
|
}
|
|
685
2339
|
}
|
|
686
2340
|
async loadWorkflowSnapshot({
|
|
@@ -688,7 +2342,7 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
688
2342
|
runId
|
|
689
2343
|
}) {
|
|
690
2344
|
try {
|
|
691
|
-
const result = await this.load({
|
|
2345
|
+
const result = await this.operations.load({
|
|
692
2346
|
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
693
2347
|
keys: {
|
|
694
2348
|
workflow_name: workflowName,
|
|
@@ -699,9 +2353,16 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
699
2353
|
return null;
|
|
700
2354
|
}
|
|
701
2355
|
return result.snapshot;
|
|
702
|
-
} catch (error) {
|
|
703
|
-
|
|
704
|
-
|
|
2356
|
+
} catch (error$1) {
|
|
2357
|
+
throw new error.MastraError(
|
|
2358
|
+
{
|
|
2359
|
+
id: "CLICKHOUSE_STORAGE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
|
|
2360
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2361
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2362
|
+
details: { workflowName, runId }
|
|
2363
|
+
},
|
|
2364
|
+
error$1
|
|
2365
|
+
);
|
|
705
2366
|
}
|
|
706
2367
|
}
|
|
707
2368
|
parseWorkflowRun(row) {
|
|
@@ -738,7 +2399,7 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
738
2399
|
values.var_workflow_name = workflowName;
|
|
739
2400
|
}
|
|
740
2401
|
if (resourceId) {
|
|
741
|
-
const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
2402
|
+
const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
|
|
742
2403
|
if (hasResourceId) {
|
|
743
2404
|
conditions.push(`resourceId = {var_resourceId:String}`);
|
|
744
2405
|
values.var_resourceId = resourceId;
|
|
@@ -759,7 +2420,7 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
759
2420
|
const offsetClause = offset !== void 0 ? `OFFSET ${offset}` : "";
|
|
760
2421
|
let total = 0;
|
|
761
2422
|
if (limit !== void 0 && offset !== void 0) {
|
|
762
|
-
const countResult = await this.
|
|
2423
|
+
const countResult = await this.client.query({
|
|
763
2424
|
query: `SELECT COUNT(*) as count FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${TABLE_ENGINES[storage.TABLE_WORKFLOW_SNAPSHOT].startsWith("ReplacingMergeTree") ? "FINAL" : ""} ${whereClause}`,
|
|
764
2425
|
query_params: values,
|
|
765
2426
|
format: "JSONEachRow"
|
|
@@ -767,21 +2428,21 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
767
2428
|
const countRows = await countResult.json();
|
|
768
2429
|
total = Number(countRows[0]?.count ?? 0);
|
|
769
2430
|
}
|
|
770
|
-
const result = await this.
|
|
2431
|
+
const result = await this.client.query({
|
|
771
2432
|
query: `
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
2433
|
+
SELECT
|
|
2434
|
+
workflow_name,
|
|
2435
|
+
run_id,
|
|
2436
|
+
snapshot,
|
|
2437
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
2438
|
+
toDateTime64(updatedAt, 3) as updatedAt,
|
|
2439
|
+
resourceId
|
|
2440
|
+
FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${TABLE_ENGINES[storage.TABLE_WORKFLOW_SNAPSHOT].startsWith("ReplacingMergeTree") ? "FINAL" : ""}
|
|
2441
|
+
${whereClause}
|
|
2442
|
+
ORDER BY createdAt DESC
|
|
2443
|
+
${limitClause}
|
|
2444
|
+
${offsetClause}
|
|
2445
|
+
`,
|
|
785
2446
|
query_params: values,
|
|
786
2447
|
format: "JSONEachRow"
|
|
787
2448
|
});
|
|
@@ -791,9 +2452,16 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
791
2452
|
return this.parseWorkflowRun(row);
|
|
792
2453
|
});
|
|
793
2454
|
return { runs, total: total || runs.length };
|
|
794
|
-
} catch (error) {
|
|
795
|
-
|
|
796
|
-
|
|
2455
|
+
} catch (error$1) {
|
|
2456
|
+
throw new error.MastraError(
|
|
2457
|
+
{
|
|
2458
|
+
id: "CLICKHOUSE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
|
|
2459
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2460
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2461
|
+
details: { workflowName: workflowName ?? "", resourceId: resourceId ?? "" }
|
|
2462
|
+
},
|
|
2463
|
+
error$1
|
|
2464
|
+
);
|
|
797
2465
|
}
|
|
798
2466
|
}
|
|
799
2467
|
async getWorkflowRunById({
|
|
@@ -812,18 +2480,19 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
812
2480
|
values.var_workflow_name = workflowName;
|
|
813
2481
|
}
|
|
814
2482
|
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
815
|
-
const result = await this.
|
|
2483
|
+
const result = await this.client.query({
|
|
816
2484
|
query: `
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
2485
|
+
SELECT
|
|
2486
|
+
workflow_name,
|
|
2487
|
+
run_id,
|
|
2488
|
+
snapshot,
|
|
2489
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
2490
|
+
toDateTime64(updatedAt, 3) as updatedAt,
|
|
2491
|
+
resourceId
|
|
2492
|
+
FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${TABLE_ENGINES[storage.TABLE_WORKFLOW_SNAPSHOT].startsWith("ReplacingMergeTree") ? "FINAL" : ""}
|
|
2493
|
+
${whereClause}
|
|
2494
|
+
ORDER BY createdAt DESC LIMIT 1
|
|
2495
|
+
`,
|
|
827
2496
|
query_params: values,
|
|
828
2497
|
format: "JSONEachRow"
|
|
829
2498
|
});
|
|
@@ -832,18 +2501,271 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
832
2501
|
return null;
|
|
833
2502
|
}
|
|
834
2503
|
return this.parseWorkflowRun(resultJson[0]);
|
|
835
|
-
} catch (error) {
|
|
836
|
-
|
|
837
|
-
|
|
2504
|
+
} catch (error$1) {
|
|
2505
|
+
throw new error.MastraError(
|
|
2506
|
+
{
|
|
2507
|
+
id: "CLICKHOUSE_STORAGE_GET_WORKFLOW_RUN_BY_ID_FAILED",
|
|
2508
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2509
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2510
|
+
details: { runId: runId ?? "", workflowName: workflowName ?? "" }
|
|
2511
|
+
},
|
|
2512
|
+
error$1
|
|
2513
|
+
);
|
|
838
2514
|
}
|
|
839
2515
|
}
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
2516
|
+
};
|
|
2517
|
+
|
|
2518
|
+
// src/storage/index.ts
|
|
2519
|
+
var ClickhouseStore = class extends storage.MastraStorage {
|
|
2520
|
+
db;
|
|
2521
|
+
ttl = {};
|
|
2522
|
+
stores;
|
|
2523
|
+
constructor(config) {
|
|
2524
|
+
super({ name: "ClickhouseStore" });
|
|
2525
|
+
this.db = client.createClient({
|
|
2526
|
+
url: config.url,
|
|
2527
|
+
username: config.username,
|
|
2528
|
+
password: config.password,
|
|
2529
|
+
clickhouse_settings: {
|
|
2530
|
+
date_time_input_format: "best_effort",
|
|
2531
|
+
date_time_output_format: "iso",
|
|
2532
|
+
// This is crucial
|
|
2533
|
+
use_client_time_zone: 1,
|
|
2534
|
+
output_format_json_quote_64bit_integers: 0
|
|
2535
|
+
}
|
|
844
2536
|
});
|
|
845
|
-
|
|
846
|
-
|
|
2537
|
+
this.ttl = config.ttl;
|
|
2538
|
+
const operations = new StoreOperationsClickhouse({ client: this.db, ttl: this.ttl });
|
|
2539
|
+
const workflows = new WorkflowsStorageClickhouse({ client: this.db, operations });
|
|
2540
|
+
const scores = new ScoresStorageClickhouse({ client: this.db, operations });
|
|
2541
|
+
const legacyEvals = new LegacyEvalsStorageClickhouse({ client: this.db, operations });
|
|
2542
|
+
const traces = new TracesStorageClickhouse({ client: this.db, operations });
|
|
2543
|
+
const memory = new MemoryStorageClickhouse({ client: this.db, operations });
|
|
2544
|
+
this.stores = {
|
|
2545
|
+
operations,
|
|
2546
|
+
workflows,
|
|
2547
|
+
scores,
|
|
2548
|
+
legacyEvals,
|
|
2549
|
+
traces,
|
|
2550
|
+
memory
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
get supports() {
|
|
2554
|
+
return {
|
|
2555
|
+
selectByIncludeResourceScope: true,
|
|
2556
|
+
resourceWorkingMemory: true,
|
|
2557
|
+
hasColumn: true,
|
|
2558
|
+
createTable: true,
|
|
2559
|
+
deleteMessages: false
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
async getEvalsByAgentName(agentName, type) {
|
|
2563
|
+
return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
|
|
2564
|
+
}
|
|
2565
|
+
async getEvals(options) {
|
|
2566
|
+
return this.stores.legacyEvals.getEvals(options);
|
|
2567
|
+
}
|
|
2568
|
+
async batchInsert({ tableName, records }) {
|
|
2569
|
+
await this.stores.operations.batchInsert({ tableName, records });
|
|
2570
|
+
}
|
|
2571
|
+
async optimizeTable({ tableName }) {
|
|
2572
|
+
try {
|
|
2573
|
+
await this.db.command({
|
|
2574
|
+
query: `OPTIMIZE TABLE ${tableName} FINAL`
|
|
2575
|
+
});
|
|
2576
|
+
} catch (error$1) {
|
|
2577
|
+
throw new error.MastraError(
|
|
2578
|
+
{
|
|
2579
|
+
id: "CLICKHOUSE_STORAGE_OPTIMIZE_TABLE_FAILED",
|
|
2580
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2581
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2582
|
+
details: { tableName }
|
|
2583
|
+
},
|
|
2584
|
+
error$1
|
|
2585
|
+
);
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
async materializeTtl({ tableName }) {
|
|
2589
|
+
try {
|
|
2590
|
+
await this.db.command({
|
|
2591
|
+
query: `ALTER TABLE ${tableName} MATERIALIZE TTL;`
|
|
2592
|
+
});
|
|
2593
|
+
} catch (error$1) {
|
|
2594
|
+
throw new error.MastraError(
|
|
2595
|
+
{
|
|
2596
|
+
id: "CLICKHOUSE_STORAGE_MATERIALIZE_TTL_FAILED",
|
|
2597
|
+
domain: error.ErrorDomain.STORAGE,
|
|
2598
|
+
category: error.ErrorCategory.THIRD_PARTY,
|
|
2599
|
+
details: { tableName }
|
|
2600
|
+
},
|
|
2601
|
+
error$1
|
|
2602
|
+
);
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
async createTable({
|
|
2606
|
+
tableName,
|
|
2607
|
+
schema
|
|
2608
|
+
}) {
|
|
2609
|
+
return this.stores.operations.createTable({ tableName, schema });
|
|
2610
|
+
}
|
|
2611
|
+
async dropTable({ tableName }) {
|
|
2612
|
+
return this.stores.operations.dropTable({ tableName });
|
|
2613
|
+
}
|
|
2614
|
+
async alterTable({
|
|
2615
|
+
tableName,
|
|
2616
|
+
schema,
|
|
2617
|
+
ifNotExists
|
|
2618
|
+
}) {
|
|
2619
|
+
return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
|
|
2620
|
+
}
|
|
2621
|
+
async clearTable({ tableName }) {
|
|
2622
|
+
return this.stores.operations.clearTable({ tableName });
|
|
2623
|
+
}
|
|
2624
|
+
async insert({ tableName, record }) {
|
|
2625
|
+
return this.stores.operations.insert({ tableName, record });
|
|
2626
|
+
}
|
|
2627
|
+
async load({ tableName, keys }) {
|
|
2628
|
+
return this.stores.operations.load({ tableName, keys });
|
|
2629
|
+
}
|
|
2630
|
+
async updateWorkflowResults({
|
|
2631
|
+
workflowName,
|
|
2632
|
+
runId,
|
|
2633
|
+
stepId,
|
|
2634
|
+
result,
|
|
2635
|
+
runtimeContext
|
|
2636
|
+
}) {
|
|
2637
|
+
return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
|
|
2638
|
+
}
|
|
2639
|
+
async updateWorkflowState({
|
|
2640
|
+
workflowName,
|
|
2641
|
+
runId,
|
|
2642
|
+
opts
|
|
2643
|
+
}) {
|
|
2644
|
+
return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
|
|
2645
|
+
}
|
|
2646
|
+
async persistWorkflowSnapshot({
|
|
2647
|
+
workflowName,
|
|
2648
|
+
runId,
|
|
2649
|
+
snapshot
|
|
2650
|
+
}) {
|
|
2651
|
+
return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
|
|
2652
|
+
}
|
|
2653
|
+
async loadWorkflowSnapshot({
|
|
2654
|
+
workflowName,
|
|
2655
|
+
runId
|
|
2656
|
+
}) {
|
|
2657
|
+
return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
|
|
2658
|
+
}
|
|
2659
|
+
async getWorkflowRuns({
|
|
2660
|
+
workflowName,
|
|
2661
|
+
fromDate,
|
|
2662
|
+
toDate,
|
|
2663
|
+
limit,
|
|
2664
|
+
offset,
|
|
2665
|
+
resourceId
|
|
2666
|
+
} = {}) {
|
|
2667
|
+
return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
|
|
2668
|
+
}
|
|
2669
|
+
async getWorkflowRunById({
|
|
2670
|
+
runId,
|
|
2671
|
+
workflowName
|
|
2672
|
+
}) {
|
|
2673
|
+
return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
|
|
2674
|
+
}
|
|
2675
|
+
async getTraces(args) {
|
|
2676
|
+
return this.stores.traces.getTraces(args);
|
|
2677
|
+
}
|
|
2678
|
+
async getTracesPaginated(args) {
|
|
2679
|
+
return this.stores.traces.getTracesPaginated(args);
|
|
2680
|
+
}
|
|
2681
|
+
async batchTraceInsert(args) {
|
|
2682
|
+
return this.stores.traces.batchTraceInsert(args);
|
|
2683
|
+
}
|
|
2684
|
+
async getThreadById({ threadId }) {
|
|
2685
|
+
return this.stores.memory.getThreadById({ threadId });
|
|
2686
|
+
}
|
|
2687
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
2688
|
+
return this.stores.memory.getThreadsByResourceId({ resourceId });
|
|
2689
|
+
}
|
|
2690
|
+
async saveThread({ thread }) {
|
|
2691
|
+
return this.stores.memory.saveThread({ thread });
|
|
2692
|
+
}
|
|
2693
|
+
async updateThread({
|
|
2694
|
+
id,
|
|
2695
|
+
title,
|
|
2696
|
+
metadata
|
|
2697
|
+
}) {
|
|
2698
|
+
return this.stores.memory.updateThread({ id, title, metadata });
|
|
2699
|
+
}
|
|
2700
|
+
async deleteThread({ threadId }) {
|
|
2701
|
+
return this.stores.memory.deleteThread({ threadId });
|
|
2702
|
+
}
|
|
2703
|
+
async getThreadsByResourceIdPaginated(args) {
|
|
2704
|
+
return this.stores.memory.getThreadsByResourceIdPaginated(args);
|
|
2705
|
+
}
|
|
2706
|
+
async getMessages({
|
|
2707
|
+
threadId,
|
|
2708
|
+
resourceId,
|
|
2709
|
+
selectBy,
|
|
2710
|
+
format
|
|
2711
|
+
}) {
|
|
2712
|
+
return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
|
|
2713
|
+
}
|
|
2714
|
+
async getMessagesById({
|
|
2715
|
+
messageIds,
|
|
2716
|
+
format
|
|
2717
|
+
}) {
|
|
2718
|
+
return this.stores.memory.getMessagesById({ messageIds, format });
|
|
2719
|
+
}
|
|
2720
|
+
async saveMessages(args) {
|
|
2721
|
+
return this.stores.memory.saveMessages(args);
|
|
2722
|
+
}
|
|
2723
|
+
async getMessagesPaginated(args) {
|
|
2724
|
+
return this.stores.memory.getMessagesPaginated(args);
|
|
2725
|
+
}
|
|
2726
|
+
async updateMessages(args) {
|
|
2727
|
+
return this.stores.memory.updateMessages(args);
|
|
2728
|
+
}
|
|
2729
|
+
async getResourceById({ resourceId }) {
|
|
2730
|
+
return this.stores.memory.getResourceById({ resourceId });
|
|
2731
|
+
}
|
|
2732
|
+
async saveResource({ resource }) {
|
|
2733
|
+
return this.stores.memory.saveResource({ resource });
|
|
2734
|
+
}
|
|
2735
|
+
async updateResource({
|
|
2736
|
+
resourceId,
|
|
2737
|
+
workingMemory,
|
|
2738
|
+
metadata
|
|
2739
|
+
}) {
|
|
2740
|
+
return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
|
|
2741
|
+
}
|
|
2742
|
+
async getScoreById({ id }) {
|
|
2743
|
+
return this.stores.scores.getScoreById({ id });
|
|
2744
|
+
}
|
|
2745
|
+
async saveScore(_score) {
|
|
2746
|
+
return this.stores.scores.saveScore(_score);
|
|
2747
|
+
}
|
|
2748
|
+
async getScoresByRunId({
|
|
2749
|
+
runId,
|
|
2750
|
+
pagination
|
|
2751
|
+
}) {
|
|
2752
|
+
return this.stores.scores.getScoresByRunId({ runId, pagination });
|
|
2753
|
+
}
|
|
2754
|
+
async getScoresByEntityId({
|
|
2755
|
+
entityId,
|
|
2756
|
+
entityType,
|
|
2757
|
+
pagination
|
|
2758
|
+
}) {
|
|
2759
|
+
return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
|
|
2760
|
+
}
|
|
2761
|
+
async getScoresByScorerId({
|
|
2762
|
+
scorerId,
|
|
2763
|
+
pagination,
|
|
2764
|
+
entityId,
|
|
2765
|
+
entityType,
|
|
2766
|
+
source
|
|
2767
|
+
}) {
|
|
2768
|
+
return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
|
|
847
2769
|
}
|
|
848
2770
|
async close() {
|
|
849
2771
|
await this.db.close();
|
|
@@ -853,3 +2775,5 @@ var ClickhouseStore = class extends storage.MastraStorage {
|
|
|
853
2775
|
exports.COLUMN_TYPES = COLUMN_TYPES;
|
|
854
2776
|
exports.ClickhouseStore = ClickhouseStore;
|
|
855
2777
|
exports.TABLE_ENGINES = TABLE_ENGINES;
|
|
2778
|
+
//# sourceMappingURL=index.cjs.map
|
|
2779
|
+
//# sourceMappingURL=index.cjs.map
|