@mastra/clickhouse 0.15.8-alpha.0 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@ var client = require('@clickhouse/client');
4
4
  var error = require('@mastra/core/error');
5
5
  var storage = require('@mastra/core/storage');
6
6
  var agent = require('@mastra/core/agent');
7
- var scores = require('@mastra/core/scores');
7
+ var evals = require('@mastra/core/evals');
8
8
 
9
9
  // src/storage/index.ts
10
10
  var TABLE_ENGINES = {
@@ -12,11 +12,10 @@ var TABLE_ENGINES = {
12
12
  [storage.TABLE_WORKFLOW_SNAPSHOT]: `ReplacingMergeTree()`,
13
13
  [storage.TABLE_TRACES]: `MergeTree()`,
14
14
  [storage.TABLE_THREADS]: `ReplacingMergeTree()`,
15
- [storage.TABLE_EVALS]: `MergeTree()`,
16
15
  [storage.TABLE_SCORERS]: `MergeTree()`,
17
16
  [storage.TABLE_RESOURCES]: `ReplacingMergeTree()`,
18
- // TODO: verify this is the correct engine for ai spans when implementing clickhouse storage
19
- [storage.TABLE_AI_SPANS]: `ReplacingMergeTree()`
17
+ // TODO: verify this is the correct engine for Spans when implementing clickhouse storage
18
+ [storage.TABLE_SPANS]: `ReplacingMergeTree()`
20
19
  };
21
20
  var COLUMN_TYPES = {
22
21
  text: "String",
@@ -47,8 +46,26 @@ function transformRows(rows) {
47
46
  return rows.map((row) => transformRow(row));
48
47
  }
49
48
 
50
- // src/storage/domains/legacy-evals/index.ts
51
- var LegacyEvalsStorageClickhouse = class extends storage.LegacyEvalsStorage {
49
+ // src/storage/domains/memory/index.ts
50
+ function serializeMetadata(metadata) {
51
+ if (!metadata || Object.keys(metadata).length === 0) {
52
+ return "{}";
53
+ }
54
+ return JSON.stringify(metadata);
55
+ }
56
+ function parseMetadata(metadata) {
57
+ if (!metadata) return {};
58
+ if (typeof metadata === "object") return metadata;
59
+ if (typeof metadata !== "string") return {};
60
+ const trimmed = metadata.trim();
61
+ if (trimmed === "" || trimmed === "null") return {};
62
+ try {
63
+ return JSON.parse(trimmed);
64
+ } catch {
65
+ return {};
66
+ }
67
+ }
68
+ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
52
69
  client;
53
70
  operations;
54
71
  constructor({ client, operations }) {
@@ -56,127 +73,122 @@ var LegacyEvalsStorageClickhouse = class extends storage.LegacyEvalsStorage {
56
73
  this.client = client;
57
74
  this.operations = operations;
58
75
  }
59
- transformEvalRow(row) {
60
- row = transformRow(row);
61
- let resultValue;
76
+ async listMessagesById({ messageIds }) {
77
+ if (messageIds.length === 0) return { messages: [] };
62
78
  try {
63
- if (row.result && typeof row.result === "string" && row.result.trim() !== "") {
64
- resultValue = JSON.parse(row.result);
65
- } else if (typeof row.result === "object" && row.result !== null) {
66
- resultValue = row.result;
67
- } else if (row.result === null || row.result === void 0 || row.result === "") {
68
- resultValue = { score: 0 };
69
- } else {
70
- throw new Error(`Invalid or empty result field: ${JSON.stringify(row.result)}`);
71
- }
72
- } catch (error$1) {
73
- console.error("Error parsing result field:", row.result, error$1);
74
- throw new error.MastraError({
75
- id: "CLICKHOUSE_STORAGE_INVALID_RESULT_FORMAT",
76
- text: `Invalid result format: ${JSON.stringify(row.result)}`,
77
- domain: error.ErrorDomain.STORAGE,
78
- category: error.ErrorCategory.USER
79
- });
80
- }
81
- let testInfoValue;
82
- try {
83
- if (row.test_info && typeof row.test_info === "string" && row.test_info.trim() !== "" && row.test_info !== "null") {
84
- testInfoValue = JSON.parse(row.test_info);
85
- } else if (typeof row.test_info === "object" && row.test_info !== null) {
86
- testInfoValue = row.test_info;
87
- }
88
- } catch {
89
- testInfoValue = void 0;
90
- }
91
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
92
- throw new error.MastraError({
93
- id: "CLICKHOUSE_STORAGE_INVALID_METRIC_FORMAT",
94
- text: `Invalid MetricResult format: ${JSON.stringify(resultValue)}`,
95
- domain: error.ErrorDomain.STORAGE,
96
- category: error.ErrorCategory.USER
97
- });
98
- }
99
- return {
100
- input: row.input,
101
- output: row.output,
102
- result: resultValue,
103
- agentName: row.agent_name,
104
- metricName: row.metric_name,
105
- instructions: row.instructions,
106
- testInfo: testInfoValue,
107
- globalRunId: row.global_run_id,
108
- runId: row.run_id,
109
- createdAt: row.created_at
110
- };
111
- }
112
- async getEvalsByAgentName(agentName, type) {
113
- try {
114
- const baseQuery = `SELECT *, toDateTime64(created_at, 3) as createdAt FROM ${storage.TABLE_EVALS} WHERE agent_name = {var_agent_name:String}`;
115
- 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') = '')" : "";
116
79
  const result = await this.client.query({
117
- query: `${baseQuery}${typeCondition} ORDER BY createdAt DESC`,
118
- query_params: { var_agent_name: agentName },
80
+ query: `
81
+ SELECT
82
+ id,
83
+ content,
84
+ role,
85
+ type,
86
+ toDateTime64(createdAt, 3) as createdAt,
87
+ thread_id AS "threadId",
88
+ "resourceId"
89
+ FROM "${storage.TABLE_MESSAGES}"
90
+ WHERE id IN {messageIds:Array(String)}
91
+ ORDER BY "createdAt" DESC
92
+ `,
93
+ query_params: {
94
+ messageIds
95
+ },
119
96
  clickhouse_settings: {
97
+ // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
120
98
  date_time_input_format: "best_effort",
121
99
  date_time_output_format: "iso",
122
100
  use_client_time_zone: 1,
123
101
  output_format_json_quote_64bit_integers: 0
124
102
  }
125
103
  });
126
- if (!result) {
127
- return [];
128
- }
129
104
  const rows = await result.json();
130
- return rows.data.map((row) => this.transformEvalRow(row));
105
+ const messages = transformRows(rows.data);
106
+ messages.forEach((message) => {
107
+ if (typeof message.content === "string") {
108
+ try {
109
+ message.content = JSON.parse(message.content);
110
+ } catch {
111
+ }
112
+ }
113
+ });
114
+ const list = new agent.MessageList().add(messages, "memory");
115
+ return { messages: list.get.all.db() };
131
116
  } catch (error$1) {
132
- if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
133
- return [];
134
- }
135
117
  throw new error.MastraError(
136
118
  {
137
- id: "CLICKHOUSE_STORAGE_GET_EVALS_BY_AGENT_FAILED",
119
+ id: "CLICKHOUSE_STORAGE_LIST_MESSAGES_BY_ID_FAILED",
138
120
  domain: error.ErrorDomain.STORAGE,
139
121
  category: error.ErrorCategory.THIRD_PARTY,
140
- details: { agentName, type: type ?? null }
122
+ details: { messageIds: JSON.stringify(messageIds) }
141
123
  },
142
124
  error$1
143
125
  );
144
126
  }
145
127
  }
146
- async getEvals(options = {}) {
147
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
148
- const fromDate = dateRange?.start;
149
- const toDate = dateRange?.end;
150
- const conditions = [];
151
- if (agentName) {
152
- conditions.push(`agent_name = {var_agent_name:String}`);
153
- }
154
- if (type === "test") {
155
- conditions.push(
156
- `(test_info IS NOT NULL AND test_info != 'null' AND JSONExtractString(test_info, 'testPath') IS NOT NULL AND JSONExtractString(test_info, 'testPath') != '')`
157
- );
158
- } else if (type === "live") {
159
- conditions.push(
160
- `(test_info IS NULL OR test_info = 'null' OR JSONExtractString(test_info, 'testPath') IS NULL OR JSONExtractString(test_info, 'testPath') = '')`
128
+ async listMessages(args) {
129
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
130
+ if (page < 0) {
131
+ throw new error.MastraError(
132
+ {
133
+ id: "STORAGE_CLICKHOUSE_LIST_MESSAGES_INVALID_PAGE",
134
+ domain: error.ErrorDomain.STORAGE,
135
+ category: error.ErrorCategory.USER,
136
+ details: { page }
137
+ },
138
+ new Error("page must be >= 0")
161
139
  );
162
140
  }
163
- if (fromDate) {
164
- conditions.push(`created_at >= parseDateTime64BestEffort({var_from_date:String})`);
165
- fromDate.toISOString();
166
- }
167
- if (toDate) {
168
- conditions.push(`created_at <= parseDateTime64BestEffort({var_to_date:String})`);
169
- toDate.toISOString();
141
+ if (!threadId.trim()) {
142
+ throw new error.MastraError(
143
+ {
144
+ id: "STORAGE_CLICKHOUSE_LIST_MESSAGES_INVALID_THREAD_ID",
145
+ domain: error.ErrorDomain.STORAGE,
146
+ category: error.ErrorCategory.THIRD_PARTY,
147
+ details: { threadId }
148
+ },
149
+ new Error("threadId must be a non-empty string")
150
+ );
170
151
  }
171
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
152
+ const perPageForQuery = storage.normalizePerPage(perPageInput, 40);
153
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPageForQuery);
172
154
  try {
173
- const countResult = await this.client.query({
174
- query: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
175
- query_params: {
176
- ...agentName ? { var_agent_name: agentName } : {},
177
- ...fromDate ? { var_from_date: fromDate.toISOString() } : {},
178
- ...toDate ? { var_to_date: toDate.toISOString() } : {}
179
- },
155
+ let dataQuery = `
156
+ SELECT
157
+ id,
158
+ content,
159
+ role,
160
+ type,
161
+ toDateTime64(createdAt, 3) as createdAt,
162
+ thread_id AS "threadId",
163
+ resourceId
164
+ FROM ${storage.TABLE_MESSAGES}
165
+ WHERE thread_id = {threadId:String}
166
+ `;
167
+ const dataParams = { threadId };
168
+ if (resourceId) {
169
+ dataQuery += ` AND resourceId = {resourceId:String}`;
170
+ dataParams.resourceId = resourceId;
171
+ }
172
+ if (filter?.dateRange?.start) {
173
+ const startDate = filter.dateRange.start instanceof Date ? filter.dateRange.start.toISOString() : new Date(filter.dateRange.start).toISOString();
174
+ dataQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
175
+ dataParams.fromDate = startDate;
176
+ }
177
+ if (filter?.dateRange?.end) {
178
+ const endDate = filter.dateRange.end instanceof Date ? filter.dateRange.end.toISOString() : new Date(filter.dateRange.end).toISOString();
179
+ dataQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
180
+ dataParams.toDate = endDate;
181
+ }
182
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
183
+ dataQuery += ` ORDER BY "${field}" ${direction}`;
184
+ if (perPageForResponse === false) ; else {
185
+ dataQuery += ` LIMIT {limit:Int64} OFFSET {offset:Int64}`;
186
+ dataParams.limit = perPageForQuery;
187
+ dataParams.offset = offset;
188
+ }
189
+ const result = await this.client.query({
190
+ query: dataQuery,
191
+ query_params: dataParams,
180
192
  clickhouse_settings: {
181
193
  date_time_input_format: "best_effort",
182
194
  date_time_output_format: "iso",
@@ -184,28 +196,28 @@ var LegacyEvalsStorageClickhouse = class extends storage.LegacyEvalsStorage {
184
196
  output_format_json_quote_64bit_integers: 0
185
197
  }
186
198
  });
187
- const countData = await countResult.json();
188
- const total = Number(countData.data?.[0]?.count ?? 0);
189
- const currentOffset = page * perPage;
190
- const hasMore = currentOffset + perPage < total;
191
- if (total === 0) {
192
- return {
193
- evals: [],
194
- total: 0,
195
- page,
196
- perPage,
197
- hasMore: false
198
- };
199
+ const rows = await result.json();
200
+ const paginatedMessages = transformRows(rows.data);
201
+ const paginatedCount = paginatedMessages.length;
202
+ let countQuery = `SELECT count() as total FROM ${storage.TABLE_MESSAGES} WHERE thread_id = {threadId:String}`;
203
+ const countParams = { threadId };
204
+ if (resourceId) {
205
+ countQuery += ` AND resourceId = {resourceId:String}`;
206
+ countParams.resourceId = resourceId;
199
207
  }
200
- const dataResult = await this.client.query({
201
- 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}`,
202
- query_params: {
203
- ...agentName ? { var_agent_name: agentName } : {},
204
- ...fromDate ? { var_from_date: fromDate.toISOString() } : {},
205
- ...toDate ? { var_to_date: toDate.toISOString() } : {},
206
- var_limit: perPage || 100,
207
- var_offset: currentOffset || 0
208
- },
208
+ if (filter?.dateRange?.start) {
209
+ const startDate = filter.dateRange.start instanceof Date ? filter.dateRange.start.toISOString() : new Date(filter.dateRange.start).toISOString();
210
+ countQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
211
+ countParams.fromDate = startDate;
212
+ }
213
+ if (filter?.dateRange?.end) {
214
+ const endDate = filter.dateRange.end instanceof Date ? filter.dateRange.end.toISOString() : new Date(filter.dateRange.end).toISOString();
215
+ countQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
216
+ countParams.toDate = endDate;
217
+ }
218
+ const countResult = await this.client.query({
219
+ query: countQuery,
220
+ query_params: countParams,
209
221
  clickhouse_settings: {
210
222
  date_time_input_format: "best_effort",
211
223
  date_time_output_format: "iso",
@@ -213,56 +225,20 @@ var LegacyEvalsStorageClickhouse = class extends storage.LegacyEvalsStorage {
213
225
  output_format_json_quote_64bit_integers: 0
214
226
  }
215
227
  });
216
- const rows = await dataResult.json();
217
- return {
218
- evals: rows.data.map((row) => this.transformEvalRow(row)),
219
- total,
220
- page,
221
- perPage,
222
- hasMore
223
- };
224
- } catch (error$1) {
225
- if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
228
+ const countData = await countResult.json();
229
+ const total = countData.data[0].total;
230
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
226
231
  return {
227
- evals: [],
232
+ messages: [],
228
233
  total: 0,
229
234
  page,
230
- perPage,
235
+ perPage: perPageForResponse,
231
236
  hasMore: false
232
237
  };
233
238
  }
234
- throw new error.MastraError(
235
- {
236
- id: "CLICKHOUSE_STORAGE_GET_EVALS_FAILED",
237
- domain: error.ErrorDomain.STORAGE,
238
- category: error.ErrorCategory.THIRD_PARTY,
239
- details: { agentName: agentName ?? "all", type: type ?? "all" }
240
- },
241
- error$1
242
- );
243
- }
244
- }
245
- };
246
- var MemoryStorageClickhouse = class extends storage.MemoryStorage {
247
- client;
248
- operations;
249
- constructor({ client, operations }) {
250
- super();
251
- this.client = client;
252
- this.operations = operations;
253
- }
254
- async getMessages({
255
- threadId,
256
- resourceId,
257
- selectBy,
258
- format
259
- }) {
260
- try {
261
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
262
- const messages = [];
263
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
264
- const include = selectBy?.include || [];
265
- if (include.length) {
239
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
240
+ let includeMessages = [];
241
+ if (include && include.length > 0) {
266
242
  const unionQueries = [];
267
243
  const params = [];
268
244
  let paramIdx = 1;
@@ -283,7 +259,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
283
259
  FROM numbered_messages
284
260
  WHERE id = {var_include_id_${paramIdx}:String}
285
261
  )
286
- SELECT DISTINCT m.id, m.content, m.role, m.type, m."createdAt", m.thread_id AS "threadId"
262
+ SELECT DISTINCT m.id, m.content, m.role, m.type, m."createdAt", m.thread_id AS "threadId", m."resourceId"
287
263
  FROM numbered_messages m
288
264
  CROSS JOIN target_positions t
289
265
  WHERE m.row_num BETWEEN (t.target_pos - {var_withPreviousMessages_${paramIdx}:Int64}) AND (t.target_pos + {var_withNextMessages_${paramIdx}:Int64})
@@ -297,7 +273,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
297
273
  );
298
274
  paramIdx++;
299
275
  }
300
- const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" DESC';
276
+ const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" ASC';
301
277
  const mergedParams = params.reduce((acc, paramObj) => ({ ...acc, ...paramObj }), {});
302
278
  const includeResult = await this.client.query({
303
279
  query: finalQuery,
@@ -309,129 +285,66 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
309
285
  output_format_json_quote_64bit_integers: 0
310
286
  }
311
287
  });
312
- const rows2 = await includeResult.json();
313
- const includedMessages = transformRows(rows2.data);
314
- const seen = /* @__PURE__ */ new Set();
315
- const dedupedMessages = includedMessages.filter((message) => {
316
- if (seen.has(message.id)) return false;
317
- seen.add(message.id);
318
- return true;
319
- });
320
- messages.push(...dedupedMessages);
321
- }
322
- const result = await this.client.query({
323
- query: `
324
- SELECT
325
- id,
326
- content,
327
- role,
328
- type,
329
- toDateTime64(createdAt, 3) as createdAt,
330
- thread_id AS "threadId"
331
- FROM "${storage.TABLE_MESSAGES}"
332
- WHERE thread_id = {threadId:String}
333
- AND id NOT IN ({exclude:Array(String)})
334
- ORDER BY "createdAt" DESC
335
- LIMIT {limit:Int64}
336
- `,
337
- query_params: {
338
- threadId,
339
- exclude: messages.map((m) => m.id),
340
- limit
341
- },
342
- clickhouse_settings: {
343
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
344
- date_time_input_format: "best_effort",
345
- date_time_output_format: "iso",
346
- use_client_time_zone: 1,
347
- output_format_json_quote_64bit_integers: 0
348
- }
349
- });
350
- const rows = await result.json();
351
- messages.push(...transformRows(rows.data));
352
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
353
- messages.forEach((message) => {
354
- if (typeof message.content === "string") {
355
- try {
356
- message.content = JSON.parse(message.content);
357
- } catch {
288
+ const includeRows = await includeResult.json();
289
+ includeMessages = transformRows(includeRows.data);
290
+ for (const includeMsg of includeMessages) {
291
+ if (!messageIds.has(includeMsg.id)) {
292
+ paginatedMessages.push(includeMsg);
293
+ messageIds.add(includeMsg.id);
358
294
  }
359
295
  }
360
- });
361
- const list = new agent.MessageList({ threadId, resourceId }).add(messages, "memory");
362
- if (format === `v2`) return list.get.all.v2();
363
- return list.get.all.v1();
364
- } catch (error$1) {
365
- throw new error.MastraError(
366
- {
367
- id: "CLICKHOUSE_STORAGE_GET_MESSAGES_FAILED",
368
- domain: error.ErrorDomain.STORAGE,
369
- category: error.ErrorCategory.THIRD_PARTY,
370
- details: { threadId, resourceId: resourceId ?? "" }
371
- },
372
- error$1
373
- );
374
- }
375
- }
376
- async getMessagesById({
377
- messageIds,
378
- format
379
- }) {
380
- if (messageIds.length === 0) return [];
381
- try {
382
- const result = await this.client.query({
383
- query: `
384
- SELECT
385
- id,
386
- content,
387
- role,
388
- type,
389
- toDateTime64(createdAt, 3) as createdAt,
390
- thread_id AS "threadId",
391
- "resourceId"
392
- FROM "${storage.TABLE_MESSAGES}"
393
- WHERE id IN {messageIds:Array(String)}
394
- ORDER BY "createdAt" DESC
395
- `,
396
- query_params: {
397
- messageIds
398
- },
399
- clickhouse_settings: {
400
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
401
- date_time_input_format: "best_effort",
402
- date_time_output_format: "iso",
403
- use_client_time_zone: 1,
404
- output_format_json_quote_64bit_integers: 0
296
+ }
297
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
298
+ let finalMessages = list.get.all.db();
299
+ finalMessages = finalMessages.sort((a, b) => {
300
+ const isDateField = field === "createdAt" || field === "updatedAt";
301
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
302
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
303
+ if (aValue === bValue) {
304
+ return a.id.localeCompare(b.id);
405
305
  }
406
- });
407
- const rows = await result.json();
408
- const messages = transformRows(rows.data);
409
- messages.forEach((message) => {
410
- if (typeof message.content === "string") {
411
- try {
412
- message.content = JSON.parse(message.content);
413
- } catch {
414
- }
306
+ if (typeof aValue === "number" && typeof bValue === "number") {
307
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
415
308
  }
309
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
416
310
  });
417
- const list = new agent.MessageList().add(messages, "memory");
418
- if (format === `v1`) return list.get.all.v1();
419
- return list.get.all.v2();
311
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
312
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
313
+ const hasMore = perPageForResponse === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
314
+ return {
315
+ messages: finalMessages,
316
+ total,
317
+ page,
318
+ perPage: perPageForResponse,
319
+ hasMore
320
+ };
420
321
  } catch (error$1) {
421
- throw new error.MastraError(
322
+ const mastraError = new error.MastraError(
422
323
  {
423
- id: "CLICKHOUSE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
324
+ id: "STORAGE_CLICKHOUSE_STORE_LIST_MESSAGES_FAILED",
424
325
  domain: error.ErrorDomain.STORAGE,
425
326
  category: error.ErrorCategory.THIRD_PARTY,
426
- details: { messageIds: JSON.stringify(messageIds) }
327
+ details: {
328
+ threadId,
329
+ resourceId: resourceId ?? ""
330
+ }
427
331
  },
428
332
  error$1
429
333
  );
334
+ this.logger?.error?.(mastraError.toString());
335
+ this.logger?.trackException?.(mastraError);
336
+ return {
337
+ messages: [],
338
+ total: 0,
339
+ page,
340
+ perPage: perPageForResponse,
341
+ hasMore: false
342
+ };
430
343
  }
431
344
  }
432
345
  async saveMessages(args) {
433
- const { messages, format = "v1" } = args;
434
- if (messages.length === 0) return messages;
346
+ const { messages } = args;
347
+ if (messages.length === 0) return { messages };
435
348
  for (const message of messages) {
436
349
  const resourceId = message.resourceId;
437
350
  if (!resourceId) {
@@ -555,7 +468,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
555
468
  id: thread.id,
556
469
  resourceId: thread.resourceId,
557
470
  title: thread.title,
558
- metadata: thread.metadata,
471
+ metadata: serializeMetadata(thread.metadata),
559
472
  createdAt: thread.createdAt,
560
473
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
561
474
  })),
@@ -567,8 +480,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
567
480
  })
568
481
  ]);
569
482
  const list = new agent.MessageList().add(messages, "memory");
570
- if (format === `v2`) return list.get.all.v2();
571
- return list.get.all.v1();
483
+ return { messages: list.get.all.db() };
572
484
  } catch (error$1) {
573
485
  throw new error.MastraError(
574
486
  {
@@ -591,8 +503,9 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
591
503
  toDateTime64(createdAt, 3) as createdAt,
592
504
  toDateTime64(updatedAt, 3) as updatedAt
593
505
  FROM "${storage.TABLE_THREADS}"
594
- FINAL
595
- WHERE id = {var_id:String}`,
506
+ WHERE id = {var_id:String}
507
+ ORDER BY updatedAt DESC
508
+ LIMIT 1`,
596
509
  query_params: { var_id: threadId },
597
510
  clickhouse_settings: {
598
511
  // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
@@ -609,7 +522,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
609
522
  }
610
523
  return {
611
524
  ...thread,
612
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
525
+ metadata: parseMetadata(thread.metadata),
613
526
  createdAt: thread.createdAt,
614
527
  updatedAt: thread.updatedAt
615
528
  };
@@ -625,47 +538,6 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
625
538
  );
626
539
  }
627
540
  }
628
- async getThreadsByResourceId({ resourceId }) {
629
- try {
630
- const result = await this.client.query({
631
- query: `SELECT
632
- id,
633
- "resourceId",
634
- title,
635
- metadata,
636
- toDateTime64(createdAt, 3) as createdAt,
637
- toDateTime64(updatedAt, 3) as updatedAt
638
- FROM "${storage.TABLE_THREADS}"
639
- WHERE "resourceId" = {var_resourceId:String}`,
640
- query_params: { var_resourceId: resourceId },
641
- clickhouse_settings: {
642
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
643
- date_time_input_format: "best_effort",
644
- date_time_output_format: "iso",
645
- use_client_time_zone: 1,
646
- output_format_json_quote_64bit_integers: 0
647
- }
648
- });
649
- const rows = await result.json();
650
- const threads = transformRows(rows.data);
651
- return threads.map((thread) => ({
652
- ...thread,
653
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
654
- createdAt: thread.createdAt,
655
- updatedAt: thread.updatedAt
656
- }));
657
- } catch (error$1) {
658
- throw new error.MastraError(
659
- {
660
- id: "CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
661
- domain: error.ErrorDomain.STORAGE,
662
- category: error.ErrorCategory.THIRD_PARTY,
663
- details: { resourceId }
664
- },
665
- error$1
666
- );
667
- }
668
- }
669
541
  async saveThread({ thread }) {
670
542
  try {
671
543
  await this.client.insert({
@@ -673,6 +545,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
673
545
  values: [
674
546
  {
675
547
  ...thread,
548
+ metadata: serializeMetadata(thread.metadata),
676
549
  createdAt: thread.createdAt.toISOString(),
677
550
  updatedAt: thread.updatedAt.toISOString()
678
551
  }
@@ -726,7 +599,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
726
599
  id: updatedThread.id,
727
600
  resourceId: updatedThread.resourceId,
728
601
  title: updatedThread.title,
729
- metadata: updatedThread.metadata,
602
+ metadata: serializeMetadata(updatedThread.metadata),
730
603
  createdAt: updatedThread.createdAt,
731
604
  updatedAt: updatedThread.updatedAt.toISOString()
732
605
  }
@@ -757,182 +630,47 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
757
630
  query_params: { var_thread_id: threadId },
758
631
  clickhouse_settings: {
759
632
  output_format_json_quote_64bit_integers: 0
760
- }
761
- });
762
- await this.client.command({
763
- query: `DELETE FROM "${storage.TABLE_THREADS}" WHERE id = {var_id:String};`,
764
- query_params: { var_id: threadId },
765
- clickhouse_settings: {
766
- output_format_json_quote_64bit_integers: 0
767
- }
768
- });
769
- } catch (error$1) {
770
- throw new error.MastraError(
771
- {
772
- id: "CLICKHOUSE_STORAGE_DELETE_THREAD_FAILED",
773
- domain: error.ErrorDomain.STORAGE,
774
- category: error.ErrorCategory.THIRD_PARTY,
775
- details: { threadId }
776
- },
777
- error$1
778
- );
779
- }
780
- }
781
- async getThreadsByResourceIdPaginated(args) {
782
- const { resourceId, page = 0, perPage = 100 } = args;
783
- try {
784
- const currentOffset = page * perPage;
785
- const countResult = await this.client.query({
786
- query: `SELECT count() as total FROM ${storage.TABLE_THREADS} WHERE resourceId = {resourceId:String}`,
787
- query_params: { resourceId },
788
- clickhouse_settings: {
789
- date_time_input_format: "best_effort",
790
- date_time_output_format: "iso",
791
- use_client_time_zone: 1,
792
- output_format_json_quote_64bit_integers: 0
793
- }
794
- });
795
- const countData = await countResult.json();
796
- const total = countData.data[0].total;
797
- if (total === 0) {
798
- return {
799
- threads: [],
800
- total: 0,
801
- page,
802
- perPage,
803
- hasMore: false
804
- };
805
- }
806
- const dataResult = await this.client.query({
807
- query: `
808
- SELECT
809
- id,
810
- resourceId,
811
- title,
812
- metadata,
813
- toDateTime64(createdAt, 3) as createdAt,
814
- toDateTime64(updatedAt, 3) as updatedAt
815
- FROM ${storage.TABLE_THREADS}
816
- WHERE resourceId = {resourceId:String}
817
- ORDER BY createdAt DESC
818
- LIMIT {limit:Int64} OFFSET {offset:Int64}
819
- `,
820
- query_params: {
821
- resourceId,
822
- limit: perPage,
823
- offset: currentOffset
824
- },
633
+ }
634
+ });
635
+ await this.client.command({
636
+ query: `DELETE FROM "${storage.TABLE_THREADS}" WHERE id = {var_id:String};`,
637
+ query_params: { var_id: threadId },
825
638
  clickhouse_settings: {
826
- date_time_input_format: "best_effort",
827
- date_time_output_format: "iso",
828
- use_client_time_zone: 1,
829
639
  output_format_json_quote_64bit_integers: 0
830
640
  }
831
641
  });
832
- const rows = await dataResult.json();
833
- const threads = transformRows(rows.data);
834
- return {
835
- threads,
836
- total,
837
- page,
838
- perPage,
839
- hasMore: currentOffset + threads.length < total
840
- };
841
642
  } catch (error$1) {
842
643
  throw new error.MastraError(
843
644
  {
844
- id: "CLICKHOUSE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
645
+ id: "CLICKHOUSE_STORAGE_DELETE_THREAD_FAILED",
845
646
  domain: error.ErrorDomain.STORAGE,
846
647
  category: error.ErrorCategory.THIRD_PARTY,
847
- details: { resourceId, page }
648
+ details: { threadId }
848
649
  },
849
650
  error$1
850
651
  );
851
652
  }
852
653
  }
853
- async getMessagesPaginated(args) {
854
- const { threadId, resourceId, selectBy, format = "v1" } = args;
855
- const page = selectBy?.pagination?.page || 0;
856
- const perPageInput = selectBy?.pagination?.perPage;
857
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 20 });
654
+ async listThreadsByResourceId(args) {
655
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
656
+ const perPage = storage.normalizePerPage(perPageInput, 100);
657
+ if (page < 0) {
658
+ throw new error.MastraError(
659
+ {
660
+ id: "STORAGE_CLICKHOUSE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
661
+ domain: error.ErrorDomain.STORAGE,
662
+ category: error.ErrorCategory.USER,
663
+ details: { page }
664
+ },
665
+ new Error("page must be >= 0")
666
+ );
667
+ }
668
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
669
+ const { field, direction } = this.parseOrderBy(orderBy);
858
670
  try {
859
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
860
- const offset = page * perPage;
861
- const dateRange = selectBy?.pagination?.dateRange;
862
- const fromDate = dateRange?.start;
863
- const toDate = dateRange?.end;
864
- const messages = [];
865
- if (selectBy?.include?.length) {
866
- const include = selectBy.include;
867
- const unionQueries = [];
868
- const params = [];
869
- let paramIdx = 1;
870
- for (const inc of include) {
871
- const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
872
- const searchId = inc.threadId || threadId;
873
- unionQueries.push(`
874
- SELECT * FROM (
875
- WITH numbered_messages AS (
876
- SELECT
877
- id, content, role, type, "createdAt", thread_id, "resourceId",
878
- ROW_NUMBER() OVER (ORDER BY "createdAt" ASC) as row_num
879
- FROM "${storage.TABLE_MESSAGES}"
880
- WHERE thread_id = {var_thread_id_${paramIdx}:String}
881
- ),
882
- target_positions AS (
883
- SELECT row_num as target_pos
884
- FROM numbered_messages
885
- WHERE id = {var_include_id_${paramIdx}:String}
886
- )
887
- SELECT DISTINCT m.id, m.content, m.role, m.type, m."createdAt", m.thread_id AS "threadId"
888
- FROM numbered_messages m
889
- CROSS JOIN target_positions t
890
- WHERE m.row_num BETWEEN (t.target_pos - {var_withPreviousMessages_${paramIdx}:Int64}) AND (t.target_pos + {var_withNextMessages_${paramIdx}:Int64})
891
- ) AS query_${paramIdx}
892
- `);
893
- params.push(
894
- { [`var_thread_id_${paramIdx}`]: searchId },
895
- { [`var_include_id_${paramIdx}`]: id },
896
- { [`var_withPreviousMessages_${paramIdx}`]: withPreviousMessages },
897
- { [`var_withNextMessages_${paramIdx}`]: withNextMessages }
898
- );
899
- paramIdx++;
900
- }
901
- const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" DESC';
902
- const mergedParams = params.reduce((acc, paramObj) => ({ ...acc, ...paramObj }), {});
903
- const includeResult = await this.client.query({
904
- query: finalQuery,
905
- query_params: mergedParams,
906
- clickhouse_settings: {
907
- date_time_input_format: "best_effort",
908
- date_time_output_format: "iso",
909
- use_client_time_zone: 1,
910
- output_format_json_quote_64bit_integers: 0
911
- }
912
- });
913
- const rows2 = await includeResult.json();
914
- const includedMessages = transformRows(rows2.data);
915
- const seen = /* @__PURE__ */ new Set();
916
- const dedupedMessages = includedMessages.filter((message) => {
917
- if (seen.has(message.id)) return false;
918
- seen.add(message.id);
919
- return true;
920
- });
921
- messages.push(...dedupedMessages);
922
- }
923
- let countQuery = `SELECT count() as total FROM ${storage.TABLE_MESSAGES} WHERE thread_id = {threadId:String}`;
924
- const countParams = { threadId };
925
- if (fromDate) {
926
- countQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
927
- countParams.fromDate = fromDate.toISOString();
928
- }
929
- if (toDate) {
930
- countQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
931
- countParams.toDate = toDate.toISOString();
932
- }
933
671
  const countResult = await this.client.query({
934
- query: countQuery,
935
- query_params: countParams,
672
+ query: `SELECT count(DISTINCT id) as total FROM ${storage.TABLE_THREADS} WHERE resourceId = {resourceId:String}`,
673
+ query_params: { resourceId },
936
674
  clickhouse_settings: {
937
675
  date_time_input_format: "best_effort",
938
676
  date_time_output_format: "iso",
@@ -942,58 +680,46 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
942
680
  });
943
681
  const countData = await countResult.json();
944
682
  const total = countData.data[0].total;
945
- if (total === 0 && messages.length === 0) {
683
+ if (total === 0) {
946
684
  return {
947
- messages: [],
685
+ threads: [],
948
686
  total: 0,
949
687
  page,
950
- perPage,
688
+ perPage: perPageForResponse,
951
689
  hasMore: false
952
690
  };
953
691
  }
954
- const excludeIds = messages.map((m) => m.id);
955
- let dataQuery = `
956
- SELECT
957
- id,
958
- content,
959
- role,
960
- type,
961
- toDateTime64(createdAt, 3) as createdAt,
962
- thread_id AS "threadId",
963
- resourceId
964
- FROM ${storage.TABLE_MESSAGES}
965
- WHERE thread_id = {threadId:String}
966
- `;
967
- const dataParams = { threadId };
968
- if (fromDate) {
969
- dataQuery += ` AND createdAt >= parseDateTime64BestEffort({fromDate:String}, 3)`;
970
- dataParams.fromDate = fromDate.toISOString();
971
- }
972
- if (toDate) {
973
- dataQuery += ` AND createdAt <= parseDateTime64BestEffort({toDate:String}, 3)`;
974
- dataParams.toDate = toDate.toISOString();
975
- }
976
- if (excludeIds.length > 0) {
977
- dataQuery += ` AND id NOT IN ({excludeIds:Array(String)})`;
978
- dataParams.excludeIds = excludeIds;
979
- }
980
- if (selectBy?.last) {
981
- dataQuery += `
982
- ORDER BY createdAt DESC
983
- LIMIT {limit:Int64}
984
- `;
985
- dataParams.limit = perPage;
986
- } else {
987
- dataQuery += `
988
- ORDER BY createdAt ASC
989
- LIMIT {limit:Int64} OFFSET {offset:Int64}
990
- `;
991
- dataParams.limit = perPage;
992
- dataParams.offset = offset;
993
- }
994
- const result = await this.client.query({
995
- query: dataQuery,
996
- query_params: dataParams,
692
+ const dataResult = await this.client.query({
693
+ query: `
694
+ WITH ranked_threads AS (
695
+ SELECT
696
+ id,
697
+ resourceId,
698
+ title,
699
+ metadata,
700
+ toDateTime64(createdAt, 3) as createdAt,
701
+ toDateTime64(updatedAt, 3) as updatedAt,
702
+ ROW_NUMBER() OVER (PARTITION BY id ORDER BY updatedAt DESC) as row_num
703
+ FROM ${storage.TABLE_THREADS}
704
+ WHERE resourceId = {resourceId:String}
705
+ )
706
+ SELECT
707
+ id,
708
+ resourceId,
709
+ title,
710
+ metadata,
711
+ createdAt,
712
+ updatedAt
713
+ FROM ranked_threads
714
+ WHERE row_num = 1
715
+ ORDER BY "${field}" ${direction === "DESC" ? "DESC" : "ASC"}
716
+ LIMIT {perPage:Int64} OFFSET {offset:Int64}
717
+ `,
718
+ query_params: {
719
+ resourceId,
720
+ perPage,
721
+ offset
722
+ },
997
723
  clickhouse_settings: {
998
724
  date_time_input_format: "best_effort",
999
725
  date_time_output_format: "iso",
@@ -1001,35 +727,28 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
1001
727
  output_format_json_quote_64bit_integers: 0
1002
728
  }
1003
729
  });
1004
- const rows = await result.json();
1005
- const paginatedMessages = transformRows(rows.data);
1006
- messages.push(...paginatedMessages);
1007
- if (selectBy?.last) {
1008
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1009
- }
730
+ const rows = await dataResult.json();
731
+ const threads = transformRows(rows.data).map((thread) => ({
732
+ ...thread,
733
+ metadata: parseMetadata(thread.metadata)
734
+ }));
1010
735
  return {
1011
- messages: format === "v2" ? messages : messages,
736
+ threads,
1012
737
  total,
1013
738
  page,
1014
- perPage,
739
+ perPage: perPageForResponse,
1015
740
  hasMore: offset + perPage < total
1016
741
  };
1017
742
  } catch (error$1) {
1018
- const mastraError = new error.MastraError(
743
+ throw new error.MastraError(
1019
744
  {
1020
- id: "CLICKHOUSE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
745
+ id: "CLICKHOUSE_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1021
746
  domain: error.ErrorDomain.STORAGE,
1022
747
  category: error.ErrorCategory.THIRD_PARTY,
1023
- details: {
1024
- threadId,
1025
- resourceId: resourceId ?? ""
1026
- }
748
+ details: { resourceId, page }
1027
749
  },
1028
750
  error$1
1029
751
  );
1030
- this.logger?.trackException?.(mastraError);
1031
- this.logger?.error?.(mastraError.toString());
1032
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1033
752
  }
1034
753
  }
1035
754
  async updateMessages(args) {
@@ -1229,7 +948,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
1229
948
  const now = (/* @__PURE__ */ new Date()).toISOString().replace("Z", "");
1230
949
  const threadUpdatePromises = Array.from(threadIdsToUpdate).map(async (threadId) => {
1231
950
  const threadResult = await this.client.query({
1232
- query: `SELECT id, resourceId, title, metadata, createdAt FROM ${storage.TABLE_THREADS} WHERE id = {threadId:String}`,
951
+ query: `SELECT id, resourceId, title, metadata, createdAt FROM ${storage.TABLE_THREADS} WHERE id = {threadId:String} ORDER BY updatedAt DESC LIMIT 1`,
1233
952
  query_params: { threadId },
1234
953
  clickhouse_settings: {
1235
954
  date_time_input_format: "best_effort",
@@ -1258,7 +977,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
1258
977
  id: existingThread.id,
1259
978
  resourceId: existingThread.resourceId,
1260
979
  title: existingThread.title,
1261
- metadata: existingThread.metadata,
980
+ metadata: typeof existingThread.metadata === "string" ? existingThread.metadata : serializeMetadata(existingThread.metadata),
1262
981
  createdAt: existingThread.createdAt,
1263
982
  updatedAt: now
1264
983
  }
@@ -1317,7 +1036,7 @@ var MemoryStorageClickhouse = class extends storage.MemoryStorage {
1317
1036
  async getResourceById({ resourceId }) {
1318
1037
  try {
1319
1038
  const result = await this.client.query({
1320
- query: `SELECT id, workingMemory, metadata, createdAt, updatedAt FROM ${storage.TABLE_RESOURCES} WHERE id = {resourceId:String}`,
1039
+ query: `SELECT id, workingMemory, metadata, createdAt, updatedAt FROM ${storage.TABLE_RESOURCES} WHERE id = {resourceId:String} ORDER BY updatedAt DESC LIMIT 1`,
1321
1040
  query_params: { resourceId },
1322
1041
  clickhouse_settings: {
1323
1042
  date_time_input_format: "best_effort",
@@ -1489,6 +1208,9 @@ var StoreOperationsClickhouse = class extends storage.StoreOperations {
1489
1208
  const columns = Object.entries(schema).map(([name, def]) => {
1490
1209
  const constraints = [];
1491
1210
  if (!def.nullable) constraints.push("NOT NULL");
1211
+ if (name === "metadata" && def.type === "text" && def.nullable) {
1212
+ constraints.push("DEFAULT '{}'");
1213
+ }
1492
1214
  const columnTtl = this.ttl?.[tableName]?.columns?.[name];
1493
1215
  return `"${name}" ${COLUMN_TYPES[def.type]} ${constraints.join(" ")} ${columnTtl ? `TTL toDateTime(${columnTtl.ttlKey ?? "createdAt"}) + INTERVAL ${columnTtl.interval} ${columnTtl.unit}` : ""}`;
1494
1216
  }).join(",\n");
@@ -1507,8 +1229,8 @@ var StoreOperationsClickhouse = class extends storage.StoreOperations {
1507
1229
  ${columns}
1508
1230
  )
1509
1231
  ENGINE = ${TABLE_ENGINES[tableName] ?? "MergeTree()"}
1510
- PRIMARY KEY (createdAt, ${tableName === storage.TABLE_EVALS ? "run_id" : "id"})
1511
- ORDER BY (createdAt, ${tableName === storage.TABLE_EVALS ? "run_id" : "id"})
1232
+ PRIMARY KEY (createdAt, ${"id"})
1233
+ ORDER BY (createdAt, ${"id"})
1512
1234
  ${this.ttl?.[tableName]?.row ? `TTL toDateTime(createdAt) + INTERVAL ${this.ttl[tableName].row.interval} ${this.ttl[tableName].row.unit}` : ""}
1513
1235
  SETTINGS index_granularity = 8192
1514
1236
  `;
@@ -1737,7 +1459,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1737
1459
  const input = storage.safelyParseJSON(row.input);
1738
1460
  const output = storage.safelyParseJSON(row.output);
1739
1461
  const additionalContext = storage.safelyParseJSON(row.additionalContext);
1740
- const runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1462
+ const requestContext = storage.safelyParseJSON(row.requestContext);
1741
1463
  const entity = storage.safelyParseJSON(row.entity);
1742
1464
  return {
1743
1465
  ...row,
@@ -1748,7 +1470,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1748
1470
  input,
1749
1471
  output,
1750
1472
  additionalContext,
1751
- runtimeContext,
1473
+ requestContext,
1752
1474
  entity,
1753
1475
  createdAt: new Date(row.createdAt),
1754
1476
  updatedAt: new Date(row.updatedAt)
@@ -1788,7 +1510,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1788
1510
  async saveScore(score) {
1789
1511
  let parsedScore;
1790
1512
  try {
1791
- parsedScore = scores.saveScorePayloadSchema.parse(score);
1513
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1792
1514
  } catch (error$1) {
1793
1515
  throw new error.MastraError(
1794
1516
  {
@@ -1827,7 +1549,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1827
1549
  );
1828
1550
  }
1829
1551
  }
1830
- async getScoresByRunId({
1552
+ async listScoresByRunId({
1831
1553
  runId,
1832
1554
  pagination
1833
1555
  }) {
@@ -1843,24 +1565,28 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1843
1565
  const countObj = countRows[0];
1844
1566
  total = Number(countObj.count);
1845
1567
  }
1568
+ const { page, perPage: perPageInput } = pagination;
1846
1569
  if (!total) {
1847
1570
  return {
1848
1571
  pagination: {
1849
1572
  total: 0,
1850
- page: pagination.page,
1851
- perPage: pagination.perPage,
1573
+ page,
1574
+ perPage: perPageInput,
1852
1575
  hasMore: false
1853
1576
  },
1854
1577
  scores: []
1855
1578
  };
1856
1579
  }
1857
- const offset = pagination.page * pagination.perPage;
1580
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1581
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1582
+ const limitValue = perPageInput === false ? total : perPage;
1583
+ const end = perPageInput === false ? total : start + perPage;
1858
1584
  const result = await this.client.query({
1859
1585
  query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE runId = {var_runId:String} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
1860
1586
  query_params: {
1861
1587
  var_runId: runId,
1862
- var_limit: pagination.perPage,
1863
- var_offset: offset
1588
+ var_limit: limitValue,
1589
+ var_offset: start
1864
1590
  },
1865
1591
  format: "JSONEachRow",
1866
1592
  clickhouse_settings: {
@@ -1875,9 +1601,9 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1875
1601
  return {
1876
1602
  pagination: {
1877
1603
  total,
1878
- page: pagination.page,
1879
- perPage: pagination.perPage,
1880
- hasMore: total > (pagination.page + 1) * pagination.perPage
1604
+ page,
1605
+ perPage: perPageForResponse,
1606
+ hasMore: end < total
1881
1607
  },
1882
1608
  scores
1883
1609
  };
@@ -1893,7 +1619,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1893
1619
  );
1894
1620
  }
1895
1621
  }
1896
- async getScoresByScorerId({
1622
+ async listScoresByScorerId({
1897
1623
  scorerId,
1898
1624
  entityId,
1899
1625
  entityType,
@@ -1927,24 +1653,28 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1927
1653
  const countObj = countRows[0];
1928
1654
  total = Number(countObj.count);
1929
1655
  }
1656
+ const { page, perPage: perPageInput } = pagination;
1930
1657
  if (!total) {
1931
1658
  return {
1932
1659
  pagination: {
1933
1660
  total: 0,
1934
- page: pagination.page,
1935
- perPage: pagination.perPage,
1661
+ page,
1662
+ perPage: perPageInput,
1936
1663
  hasMore: false
1937
1664
  },
1938
1665
  scores: []
1939
1666
  };
1940
1667
  }
1941
- const offset = pagination.page * pagination.perPage;
1668
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1669
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1670
+ const limitValue = perPageInput === false ? total : perPage;
1671
+ const end = perPageInput === false ? total : start + perPage;
1942
1672
  const result = await this.client.query({
1943
1673
  query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE ${whereClause} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
1944
1674
  query_params: {
1945
1675
  var_scorerId: scorerId,
1946
- var_limit: pagination.perPage,
1947
- var_offset: offset,
1676
+ var_limit: limitValue,
1677
+ var_offset: start,
1948
1678
  var_entityId: entityId,
1949
1679
  var_entityType: entityType,
1950
1680
  var_source: source
@@ -1962,9 +1692,9 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1962
1692
  return {
1963
1693
  pagination: {
1964
1694
  total,
1965
- page: pagination.page,
1966
- perPage: pagination.perPage,
1967
- hasMore: total > (pagination.page + 1) * pagination.perPage
1695
+ page,
1696
+ perPage: perPageForResponse,
1697
+ hasMore: end < total
1968
1698
  },
1969
1699
  scores
1970
1700
  };
@@ -1980,7 +1710,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1980
1710
  );
1981
1711
  }
1982
1712
  }
1983
- async getScoresByEntityId({
1713
+ async listScoresByEntityId({
1984
1714
  entityId,
1985
1715
  entityType,
1986
1716
  pagination
@@ -1997,25 +1727,29 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
1997
1727
  const countObj = countRows[0];
1998
1728
  total = Number(countObj.count);
1999
1729
  }
1730
+ const { page, perPage: perPageInput } = pagination;
2000
1731
  if (!total) {
2001
1732
  return {
2002
1733
  pagination: {
2003
1734
  total: 0,
2004
- page: pagination.page,
2005
- perPage: pagination.perPage,
1735
+ page,
1736
+ perPage: perPageInput,
2006
1737
  hasMore: false
2007
1738
  },
2008
1739
  scores: []
2009
1740
  };
2010
1741
  }
2011
- const offset = pagination.page * pagination.perPage;
1742
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1743
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1744
+ const limitValue = perPageInput === false ? total : perPage;
1745
+ const end = perPageInput === false ? total : start + perPage;
2012
1746
  const result = await this.client.query({
2013
1747
  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}`,
2014
1748
  query_params: {
2015
1749
  var_entityId: entityId,
2016
1750
  var_entityType: entityType,
2017
- var_limit: pagination.perPage,
2018
- var_offset: offset
1751
+ var_limit: limitValue,
1752
+ var_offset: start
2019
1753
  },
2020
1754
  format: "JSONEachRow",
2021
1755
  clickhouse_settings: {
@@ -2030,9 +1764,9 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
2030
1764
  return {
2031
1765
  pagination: {
2032
1766
  total,
2033
- page: pagination.page,
2034
- perPage: pagination.perPage,
2035
- hasMore: total > (pagination.page + 1) * pagination.perPage
1767
+ page,
1768
+ perPage: perPageForResponse,
1769
+ hasMore: end < total
2036
1770
  },
2037
1771
  scores
2038
1772
  };
@@ -2048,7 +1782,7 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
2048
1782
  );
2049
1783
  }
2050
1784
  }
2051
- async getScoresBySpan({
1785
+ async listScoresBySpan({
2052
1786
  traceId,
2053
1787
  spanId,
2054
1788
  pagination
@@ -2068,26 +1802,29 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
2068
1802
  const countObj = countRows[0];
2069
1803
  total = Number(countObj.count);
2070
1804
  }
1805
+ const { page, perPage: perPageInput } = pagination;
2071
1806
  if (!total) {
2072
1807
  return {
2073
1808
  pagination: {
2074
1809
  total: 0,
2075
- page: pagination.page,
2076
- perPage: pagination.perPage,
1810
+ page,
1811
+ perPage: perPageInput,
2077
1812
  hasMore: false
2078
1813
  },
2079
1814
  scores: []
2080
1815
  };
2081
1816
  }
2082
- const limit = pagination.perPage + 1;
2083
- const offset = pagination.page * pagination.perPage;
1817
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1818
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1819
+ const limitValue = perPageInput === false ? total : perPage;
1820
+ const end = perPageInput === false ? total : start + perPage;
2084
1821
  const result = await this.client.query({
2085
1822
  query: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE traceId = {var_traceId:String} AND spanId = {var_spanId:String} ORDER BY createdAt DESC LIMIT {var_limit:Int64} OFFSET {var_offset:Int64}`,
2086
1823
  query_params: {
2087
1824
  var_traceId: traceId,
2088
1825
  var_spanId: spanId,
2089
- var_limit: limit,
2090
- var_offset: offset
1826
+ var_limit: limitValue,
1827
+ var_offset: start
2091
1828
  },
2092
1829
  format: "JSONEachRow",
2093
1830
  clickhouse_settings: {
@@ -2098,15 +1835,13 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
2098
1835
  }
2099
1836
  });
2100
1837
  const rows = await result.json();
2101
- const transformedRows = Array.isArray(rows) ? rows.map((row) => this.transformScoreRow(row)) : [];
2102
- const hasMore = transformedRows.length > pagination.perPage;
2103
- const scores = hasMore ? transformedRows.slice(0, pagination.perPage) : transformedRows;
1838
+ const scores = Array.isArray(rows) ? rows.map((row) => this.transformScoreRow(row)) : [];
2104
1839
  return {
2105
1840
  pagination: {
2106
1841
  total,
2107
- page: pagination.page,
2108
- perPage: pagination.perPage,
2109
- hasMore
1842
+ page,
1843
+ perPage: perPageForResponse,
1844
+ hasMore: end < total
2110
1845
  },
2111
1846
  scores
2112
1847
  };
@@ -2123,249 +1858,6 @@ var ScoresStorageClickhouse = class extends storage.ScoresStorage {
2123
1858
  }
2124
1859
  }
2125
1860
  };
2126
- var TracesStorageClickhouse = class extends storage.TracesStorage {
2127
- client;
2128
- operations;
2129
- constructor({ client, operations }) {
2130
- super();
2131
- this.client = client;
2132
- this.operations = operations;
2133
- }
2134
- async getTracesPaginated(args) {
2135
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2136
- const fromDate = dateRange?.start;
2137
- const toDate = dateRange?.end;
2138
- const currentOffset = page * perPage;
2139
- const queryArgs = {};
2140
- const conditions = [];
2141
- if (name) {
2142
- conditions.push(`name LIKE CONCAT({var_name:String}, '%')`);
2143
- queryArgs.var_name = name;
2144
- }
2145
- if (scope) {
2146
- conditions.push(`scope = {var_scope:String}`);
2147
- queryArgs.var_scope = scope;
2148
- }
2149
- if (attributes) {
2150
- Object.entries(attributes).forEach(([key, value]) => {
2151
- conditions.push(`JSONExtractString(attributes, '${key}') = {var_attr_${key}:String}`);
2152
- queryArgs[`var_attr_${key}`] = value;
2153
- });
2154
- }
2155
- if (filters) {
2156
- Object.entries(filters).forEach(([key, value]) => {
2157
- conditions.push(`${key} = {var_col_${key}:${storage.TABLE_SCHEMAS.mastra_traces?.[key]?.type ?? "text"}}`);
2158
- queryArgs[`var_col_${key}`] = value;
2159
- });
2160
- }
2161
- if (fromDate) {
2162
- conditions.push(`createdAt >= parseDateTime64BestEffort({var_from_date:String})`);
2163
- queryArgs.var_from_date = fromDate.toISOString();
2164
- }
2165
- if (toDate) {
2166
- conditions.push(`createdAt <= parseDateTime64BestEffort({var_to_date:String})`);
2167
- queryArgs.var_to_date = toDate.toISOString();
2168
- }
2169
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2170
- try {
2171
- const countResult = await this.client.query({
2172
- query: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
2173
- query_params: queryArgs,
2174
- clickhouse_settings: {
2175
- date_time_input_format: "best_effort",
2176
- date_time_output_format: "iso",
2177
- use_client_time_zone: 1,
2178
- output_format_json_quote_64bit_integers: 0
2179
- }
2180
- });
2181
- const countData = await countResult.json();
2182
- const total = Number(countData.data?.[0]?.count ?? 0);
2183
- if (total === 0) {
2184
- return {
2185
- traces: [],
2186
- total: 0,
2187
- page,
2188
- perPage,
2189
- hasMore: false
2190
- };
2191
- }
2192
- const result = await this.client.query({
2193
- query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT {var_limit:UInt32} OFFSET {var_offset:UInt32}`,
2194
- query_params: { ...queryArgs, var_limit: perPage, var_offset: currentOffset },
2195
- clickhouse_settings: {
2196
- date_time_input_format: "best_effort",
2197
- date_time_output_format: "iso",
2198
- use_client_time_zone: 1,
2199
- output_format_json_quote_64bit_integers: 0
2200
- }
2201
- });
2202
- if (!result) {
2203
- return {
2204
- traces: [],
2205
- total,
2206
- page,
2207
- perPage,
2208
- hasMore: false
2209
- };
2210
- }
2211
- const resp = await result.json();
2212
- const rows = resp.data;
2213
- const traces = rows.map((row) => ({
2214
- id: row.id,
2215
- parentSpanId: row.parentSpanId,
2216
- traceId: row.traceId,
2217
- name: row.name,
2218
- scope: row.scope,
2219
- kind: row.kind,
2220
- status: storage.safelyParseJSON(row.status),
2221
- events: storage.safelyParseJSON(row.events),
2222
- links: storage.safelyParseJSON(row.links),
2223
- attributes: storage.safelyParseJSON(row.attributes),
2224
- startTime: row.startTime,
2225
- endTime: row.endTime,
2226
- other: storage.safelyParseJSON(row.other),
2227
- createdAt: row.createdAt
2228
- }));
2229
- return {
2230
- traces,
2231
- total,
2232
- page,
2233
- perPage,
2234
- hasMore: currentOffset + traces.length < total
2235
- };
2236
- } catch (error$1) {
2237
- if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
2238
- return {
2239
- traces: [],
2240
- total: 0,
2241
- page,
2242
- perPage,
2243
- hasMore: false
2244
- };
2245
- }
2246
- throw new error.MastraError(
2247
- {
2248
- id: "CLICKHOUSE_STORAGE_GET_TRACES_PAGINATED_FAILED",
2249
- domain: error.ErrorDomain.STORAGE,
2250
- category: error.ErrorCategory.THIRD_PARTY,
2251
- details: {
2252
- name: name ?? null,
2253
- scope: scope ?? null,
2254
- page,
2255
- perPage,
2256
- attributes: attributes ? JSON.stringify(attributes) : null,
2257
- filters: filters ? JSON.stringify(filters) : null,
2258
- dateRange: dateRange ? JSON.stringify(dateRange) : null
2259
- }
2260
- },
2261
- error$1
2262
- );
2263
- }
2264
- }
2265
- async getTraces({
2266
- name,
2267
- scope,
2268
- page,
2269
- perPage,
2270
- attributes,
2271
- filters,
2272
- fromDate,
2273
- toDate
2274
- }) {
2275
- const limit = perPage;
2276
- const offset = page * perPage;
2277
- const args = {};
2278
- const conditions = [];
2279
- if (name) {
2280
- conditions.push(`name LIKE CONCAT({var_name:String}, '%')`);
2281
- args.var_name = name;
2282
- }
2283
- if (scope) {
2284
- conditions.push(`scope = {var_scope:String}`);
2285
- args.var_scope = scope;
2286
- }
2287
- if (attributes) {
2288
- Object.entries(attributes).forEach(([key, value]) => {
2289
- conditions.push(`JSONExtractString(attributes, '${key}') = {var_attr_${key}:String}`);
2290
- args[`var_attr_${key}`] = value;
2291
- });
2292
- }
2293
- if (filters) {
2294
- Object.entries(filters).forEach(([key, value]) => {
2295
- conditions.push(`${key} = {var_col_${key}:${storage.TABLE_SCHEMAS.mastra_traces?.[key]?.type ?? "text"}}`);
2296
- args[`var_col_${key}`] = value;
2297
- });
2298
- }
2299
- if (fromDate) {
2300
- conditions.push(`createdAt >= {var_from_date:DateTime64(3)}`);
2301
- args.var_from_date = fromDate.getTime() / 1e3;
2302
- }
2303
- if (toDate) {
2304
- conditions.push(`createdAt <= {var_to_date:DateTime64(3)}`);
2305
- args.var_to_date = toDate.getTime() / 1e3;
2306
- }
2307
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2308
- try {
2309
- const result = await this.client.query({
2310
- query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
2311
- query_params: args,
2312
- clickhouse_settings: {
2313
- // Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
2314
- date_time_input_format: "best_effort",
2315
- date_time_output_format: "iso",
2316
- use_client_time_zone: 1,
2317
- output_format_json_quote_64bit_integers: 0
2318
- }
2319
- });
2320
- if (!result) {
2321
- return [];
2322
- }
2323
- const resp = await result.json();
2324
- const rows = resp.data;
2325
- return rows.map((row) => ({
2326
- id: row.id,
2327
- parentSpanId: row.parentSpanId,
2328
- traceId: row.traceId,
2329
- name: row.name,
2330
- scope: row.scope,
2331
- kind: row.kind,
2332
- status: storage.safelyParseJSON(row.status),
2333
- events: storage.safelyParseJSON(row.events),
2334
- links: storage.safelyParseJSON(row.links),
2335
- attributes: storage.safelyParseJSON(row.attributes),
2336
- startTime: row.startTime,
2337
- endTime: row.endTime,
2338
- other: storage.safelyParseJSON(row.other),
2339
- createdAt: row.createdAt
2340
- }));
2341
- } catch (error$1) {
2342
- if (error$1?.message?.includes("no such table") || error$1?.message?.includes("does not exist")) {
2343
- return [];
2344
- }
2345
- throw new error.MastraError(
2346
- {
2347
- id: "CLICKHOUSE_STORAGE_GET_TRACES_FAILED",
2348
- domain: error.ErrorDomain.STORAGE,
2349
- category: error.ErrorCategory.THIRD_PARTY,
2350
- details: {
2351
- name: name ?? null,
2352
- scope: scope ?? null,
2353
- page,
2354
- perPage,
2355
- attributes: attributes ? JSON.stringify(attributes) : null,
2356
- filters: filters ? JSON.stringify(filters) : null,
2357
- fromDate: fromDate?.toISOString() ?? null,
2358
- toDate: toDate?.toISOString() ?? null
2359
- }
2360
- },
2361
- error$1
2362
- );
2363
- }
2364
- }
2365
- async batchTraceInsert(args) {
2366
- await this.operations.batchInsert({ tableName: storage.TABLE_TRACES, records: args.records });
2367
- }
2368
- };
2369
1861
  var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
2370
1862
  client;
2371
1863
  operations;
@@ -2379,7 +1871,7 @@ var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
2379
1871
  // runId,
2380
1872
  // stepId,
2381
1873
  // result,
2382
- // runtimeContext,
1874
+ // requestContext,
2383
1875
  }) {
2384
1876
  throw new Error("Method not implemented.");
2385
1877
  }
@@ -2484,12 +1976,12 @@ var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
2484
1976
  resourceId: row.resourceId
2485
1977
  };
2486
1978
  }
2487
- async getWorkflowRuns({
1979
+ async listWorkflowRuns({
2488
1980
  workflowName,
2489
1981
  fromDate,
2490
1982
  toDate,
2491
- limit,
2492
- offset,
1983
+ page,
1984
+ perPage,
2493
1985
  resourceId
2494
1986
  } = {}) {
2495
1987
  try {
@@ -2517,10 +2009,13 @@ var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
2517
2009
  values.var_to_date = toDate.getTime() / 1e3;
2518
2010
  }
2519
2011
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2520
- const limitClause = limit !== void 0 ? `LIMIT ${limit}` : "";
2521
- const offsetClause = offset !== void 0 ? `OFFSET ${offset}` : "";
2012
+ const usePagination = perPage !== void 0 && page !== void 0;
2013
+ const normalizedPerPage = usePagination ? storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER) : 0;
2014
+ const offset = usePagination ? page * normalizedPerPage : 0;
2015
+ const limitClause = usePagination ? `LIMIT ${normalizedPerPage}` : "";
2016
+ const offsetClause = usePagination ? `OFFSET ${offset}` : "";
2522
2017
  let total = 0;
2523
- if (limit !== void 0 && offset !== void 0) {
2018
+ if (usePagination) {
2524
2019
  const countResult = await this.client.query({
2525
2020
  query: `SELECT COUNT(*) as count FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${TABLE_ENGINES[storage.TABLE_WORKFLOW_SNAPSHOT].startsWith("ReplacingMergeTree") ? "FINAL" : ""} ${whereClause}`,
2526
2021
  query_params: values,
@@ -2556,7 +2051,7 @@ var WorkflowsStorageClickhouse = class extends storage.WorkflowsStorage {
2556
2051
  } catch (error$1) {
2557
2052
  throw new error.MastraError(
2558
2053
  {
2559
- id: "CLICKHOUSE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
2054
+ id: "CLICKHOUSE_STORAGE_LIST_WORKFLOW_RUNS_FAILED",
2560
2055
  domain: error.ErrorDomain.STORAGE,
2561
2056
  category: error.ErrorCategory.THIRD_PARTY,
2562
2057
  details: { workflowName: workflowName ?? "", resourceId: resourceId ?? "" }
@@ -2622,7 +2117,7 @@ var ClickhouseStore = class extends storage.MastraStorage {
2622
2117
  ttl = {};
2623
2118
  stores;
2624
2119
  constructor(config) {
2625
- super({ name: "ClickhouseStore" });
2120
+ super({ id: config.id, name: "ClickhouseStore" });
2626
2121
  this.db = client.createClient({
2627
2122
  url: config.url,
2628
2123
  username: config.username,
@@ -2639,15 +2134,11 @@ var ClickhouseStore = class extends storage.MastraStorage {
2639
2134
  const operations = new StoreOperationsClickhouse({ client: this.db, ttl: this.ttl });
2640
2135
  const workflows = new WorkflowsStorageClickhouse({ client: this.db, operations });
2641
2136
  const scores = new ScoresStorageClickhouse({ client: this.db, operations });
2642
- const legacyEvals = new LegacyEvalsStorageClickhouse({ client: this.db, operations });
2643
- const traces = new TracesStorageClickhouse({ client: this.db, operations });
2644
2137
  const memory = new MemoryStorageClickhouse({ client: this.db, operations });
2645
2138
  this.stores = {
2646
2139
  operations,
2647
2140
  workflows,
2648
2141
  scores,
2649
- legacyEvals,
2650
- traces,
2651
2142
  memory
2652
2143
  };
2653
2144
  }
@@ -2658,15 +2149,9 @@ var ClickhouseStore = class extends storage.MastraStorage {
2658
2149
  hasColumn: true,
2659
2150
  createTable: true,
2660
2151
  deleteMessages: false,
2661
- getScoresBySpan: true
2152
+ listScoresBySpan: true
2662
2153
  };
2663
2154
  }
2664
- async getEvalsByAgentName(agentName, type) {
2665
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2666
- }
2667
- async getEvals(options) {
2668
- return this.stores.legacyEvals.getEvals(options);
2669
- }
2670
2155
  async batchInsert({ tableName, records }) {
2671
2156
  await this.stores.operations.batchInsert({ tableName, records });
2672
2157
  }
@@ -2734,9 +2219,9 @@ var ClickhouseStore = class extends storage.MastraStorage {
2734
2219
  runId,
2735
2220
  stepId,
2736
2221
  result,
2737
- runtimeContext
2222
+ requestContext
2738
2223
  }) {
2739
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2224
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2740
2225
  }
2741
2226
  async updateWorkflowState({
2742
2227
  workflowName,
@@ -2759,15 +2244,15 @@ var ClickhouseStore = class extends storage.MastraStorage {
2759
2244
  }) {
2760
2245
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2761
2246
  }
2762
- async getWorkflowRuns({
2247
+ async listWorkflowRuns({
2763
2248
  workflowName,
2764
2249
  fromDate,
2765
2250
  toDate,
2766
- limit,
2767
- offset,
2251
+ perPage,
2252
+ page,
2768
2253
  resourceId
2769
2254
  } = {}) {
2770
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2255
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
2771
2256
  }
2772
2257
  async getWorkflowRunById({
2773
2258
  runId,
@@ -2775,21 +2260,9 @@ var ClickhouseStore = class extends storage.MastraStorage {
2775
2260
  }) {
2776
2261
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2777
2262
  }
2778
- async getTraces(args) {
2779
- return this.stores.traces.getTraces(args);
2780
- }
2781
- async getTracesPaginated(args) {
2782
- return this.stores.traces.getTracesPaginated(args);
2783
- }
2784
- async batchTraceInsert(args) {
2785
- return this.stores.traces.batchTraceInsert(args);
2786
- }
2787
2263
  async getThreadById({ threadId }) {
2788
2264
  return this.stores.memory.getThreadById({ threadId });
2789
2265
  }
2790
- async getThreadsByResourceId({ resourceId }) {
2791
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2792
- }
2793
2266
  async saveThread({ thread }) {
2794
2267
  return this.stores.memory.saveThread({ thread });
2795
2268
  }
@@ -2803,29 +2276,9 @@ var ClickhouseStore = class extends storage.MastraStorage {
2803
2276
  async deleteThread({ threadId }) {
2804
2277
  return this.stores.memory.deleteThread({ threadId });
2805
2278
  }
2806
- async getThreadsByResourceIdPaginated(args) {
2807
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2808
- }
2809
- async getMessages({
2810
- threadId,
2811
- resourceId,
2812
- selectBy,
2813
- format
2814
- }) {
2815
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2816
- }
2817
- async getMessagesById({
2818
- messageIds,
2819
- format
2820
- }) {
2821
- return this.stores.memory.getMessagesById({ messageIds, format });
2822
- }
2823
2279
  async saveMessages(args) {
2824
2280
  return this.stores.memory.saveMessages(args);
2825
2281
  }
2826
- async getMessagesPaginated(args) {
2827
- return this.stores.memory.getMessagesPaginated(args);
2828
- }
2829
2282
  async updateMessages(args) {
2830
2283
  return this.stores.memory.updateMessages(args);
2831
2284
  }
@@ -2848,34 +2301,34 @@ var ClickhouseStore = class extends storage.MastraStorage {
2848
2301
  async saveScore(_score) {
2849
2302
  return this.stores.scores.saveScore(_score);
2850
2303
  }
2851
- async getScoresByRunId({
2304
+ async listScoresByRunId({
2852
2305
  runId,
2853
2306
  pagination
2854
2307
  }) {
2855
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2308
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2856
2309
  }
2857
- async getScoresByEntityId({
2310
+ async listScoresByEntityId({
2858
2311
  entityId,
2859
2312
  entityType,
2860
2313
  pagination
2861
2314
  }) {
2862
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2315
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2863
2316
  }
2864
- async getScoresByScorerId({
2317
+ async listScoresByScorerId({
2865
2318
  scorerId,
2866
2319
  pagination,
2867
2320
  entityId,
2868
2321
  entityType,
2869
2322
  source
2870
2323
  }) {
2871
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2324
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2872
2325
  }
2873
- async getScoresBySpan({
2326
+ async listScoresBySpan({
2874
2327
  traceId,
2875
2328
  spanId,
2876
2329
  pagination
2877
2330
  }) {
2878
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2331
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2879
2332
  }
2880
2333
  async close() {
2881
2334
  await this.db.close();