@mastra/convex 0.0.0-feat-improve-processors-20251205191721

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE.md +15 -0
  3. package/README.md +123 -0
  4. package/dist/chunk-NZCHEPNU.js +362 -0
  5. package/dist/chunk-NZCHEPNU.js.map +1 -0
  6. package/dist/chunk-QKN2PWR2.cjs +391 -0
  7. package/dist/chunk-QKN2PWR2.cjs.map +1 -0
  8. package/dist/index.cjs +1350 -0
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +1287 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/server/index.cjs +64 -0
  15. package/dist/server/index.cjs.map +1 -0
  16. package/dist/server/index.d.ts +3 -0
  17. package/dist/server/index.d.ts.map +1 -0
  18. package/dist/server/index.js +3 -0
  19. package/dist/server/index.js.map +1 -0
  20. package/dist/server/schema.d.ts +115 -0
  21. package/dist/server/schema.d.ts.map +1 -0
  22. package/dist/server/storage.d.ts +7 -0
  23. package/dist/server/storage.d.ts.map +1 -0
  24. package/dist/storage/client.d.ts +24 -0
  25. package/dist/storage/client.d.ts.map +1 -0
  26. package/dist/storage/domains/memory.d.ts +59 -0
  27. package/dist/storage/domains/memory.d.ts.map +1 -0
  28. package/dist/storage/domains/scores.d.ts +42 -0
  29. package/dist/storage/domains/scores.d.ts.map +1 -0
  30. package/dist/storage/domains/workflows.d.ts +44 -0
  31. package/dist/storage/domains/workflows.d.ts.map +1 -0
  32. package/dist/storage/index.d.ts +161 -0
  33. package/dist/storage/index.d.ts.map +1 -0
  34. package/dist/storage/operations.d.ts +40 -0
  35. package/dist/storage/operations.d.ts.map +1 -0
  36. package/dist/storage/types.d.ts +42 -0
  37. package/dist/storage/types.d.ts.map +1 -0
  38. package/dist/vector/index.d.ts +35 -0
  39. package/dist/vector/index.d.ts.map +1 -0
  40. package/package.json +75 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,1350 @@
1
+ 'use strict';
2
+
3
+ var chunkQKN2PWR2_cjs = require('./chunk-QKN2PWR2.cjs');
4
+ var storage = require('@mastra/core/storage');
5
+ var agent = require('@mastra/core/agent');
6
+ var error = require('@mastra/core/error');
7
+ var crypto = require('crypto');
8
+ var vector = require('@mastra/core/vector');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
13
+
14
+ // src/storage/client.ts
15
+ var DEFAULT_STORAGE_FUNCTION = "mastra/storage:handle";
16
+ var ConvexAdminClient = class {
17
+ deploymentUrl;
18
+ adminAuthToken;
19
+ storageFunction;
20
+ constructor({ deploymentUrl, adminAuthToken, storageFunction }) {
21
+ if (!deploymentUrl) {
22
+ throw new Error("ConvexAdminClient: deploymentUrl is required.");
23
+ }
24
+ if (!adminAuthToken) {
25
+ throw new Error("ConvexAdminClient: adminAuthToken is required.");
26
+ }
27
+ this.deploymentUrl = deploymentUrl.replace(/\/$/, "");
28
+ this.adminAuthToken = adminAuthToken;
29
+ this.storageFunction = storageFunction ?? DEFAULT_STORAGE_FUNCTION;
30
+ }
31
+ /**
32
+ * Call storage and return the full response including hasMore flag.
33
+ * Use this for operations that may need multiple calls (e.g., clearTable).
34
+ */
35
+ async callStorageRaw(request) {
36
+ const url = `${this.deploymentUrl}/api/mutation`;
37
+ const response = await fetch(url, {
38
+ method: "POST",
39
+ headers: {
40
+ "Content-Type": "application/json",
41
+ Authorization: `Convex ${this.adminAuthToken}`
42
+ },
43
+ body: JSON.stringify({
44
+ path: this.storageFunction,
45
+ args: request,
46
+ format: "json"
47
+ })
48
+ });
49
+ if (!response.ok) {
50
+ const text = await response.text();
51
+ throw new Error(`Convex API error: ${response.status} ${text}`);
52
+ }
53
+ const result = await response.json();
54
+ if (result.status === "error") {
55
+ const error = new Error(result.errorMessage || "Unknown Convex error");
56
+ error.code = result.errorCode;
57
+ throw error;
58
+ }
59
+ const storageResponse = result.value;
60
+ if (!storageResponse?.ok) {
61
+ const errResponse = storageResponse;
62
+ const error = new Error(errResponse?.error || "Unknown Convex storage error");
63
+ error.code = errResponse?.code;
64
+ error.details = errResponse?.details;
65
+ throw error;
66
+ }
67
+ return {
68
+ result: storageResponse.result,
69
+ hasMore: storageResponse.hasMore
70
+ };
71
+ }
72
+ async callStorage(request) {
73
+ const { result } = await this.callStorageRaw(request);
74
+ return result;
75
+ }
76
+ };
77
+ var MemoryConvex = class extends storage.MemoryStorage {
78
+ constructor(operations) {
79
+ super();
80
+ this.operations = operations;
81
+ }
82
+ async getThreadById({ threadId }) {
83
+ const row = await this.operations.load({
84
+ tableName: storage.TABLE_THREADS,
85
+ keys: { id: threadId }
86
+ });
87
+ if (!row) return null;
88
+ return {
89
+ ...row,
90
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata,
91
+ createdAt: new Date(row.createdAt),
92
+ updatedAt: new Date(row.updatedAt)
93
+ };
94
+ }
95
+ async saveThread({ thread }) {
96
+ await this.operations.insert({
97
+ tableName: storage.TABLE_THREADS,
98
+ record: {
99
+ ...thread,
100
+ metadata: thread.metadata ?? {}
101
+ }
102
+ });
103
+ return thread;
104
+ }
105
+ async updateThread({
106
+ id,
107
+ title,
108
+ metadata
109
+ }) {
110
+ const existing = await this.getThreadById({ threadId: id });
111
+ if (!existing) {
112
+ throw new error.MastraError({
113
+ id: "CONVEX_STORAGE_THREAD_NOT_FOUND",
114
+ domain: error.ErrorDomain.STORAGE,
115
+ category: error.ErrorCategory.USER,
116
+ text: `Thread ${id} not found`
117
+ });
118
+ }
119
+ const updated = {
120
+ ...existing,
121
+ title,
122
+ metadata: {
123
+ ...existing.metadata,
124
+ ...metadata
125
+ },
126
+ updatedAt: /* @__PURE__ */ new Date()
127
+ };
128
+ await this.saveThread({ thread: updated });
129
+ return updated;
130
+ }
131
+ async deleteThread({ threadId }) {
132
+ const messages = await this.operations.queryTable(storage.TABLE_MESSAGES, [
133
+ { field: "thread_id", value: threadId }
134
+ ]);
135
+ await this.operations.deleteMany(
136
+ storage.TABLE_MESSAGES,
137
+ messages.map((msg) => msg.id)
138
+ );
139
+ await this.operations.deleteMany(storage.TABLE_THREADS, [threadId]);
140
+ }
141
+ async listThreadsByResourceId(args) {
142
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
143
+ const perPage = storage.normalizePerPage(perPageInput, 100);
144
+ const { field, direction } = this.parseOrderBy(orderBy);
145
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
146
+ const rows = await this.operations.queryTable(storage.TABLE_THREADS, [{ field: "resourceId", value: resourceId }]);
147
+ const threads = rows.map((row) => ({
148
+ ...row,
149
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata,
150
+ createdAt: new Date(row.createdAt),
151
+ updatedAt: new Date(row.updatedAt)
152
+ }));
153
+ threads.sort((a, b) => {
154
+ const aValue = a[field];
155
+ const bValue = b[field];
156
+ const aTime = aValue instanceof Date ? aValue.getTime() : new Date(aValue).getTime();
157
+ const bTime = bValue instanceof Date ? bValue.getTime() : new Date(bValue).getTime();
158
+ return direction === "ASC" ? aTime - bTime : bTime - aTime;
159
+ });
160
+ const total = threads.length;
161
+ const paginated = perPageInput === false ? threads : threads.slice(offset, offset + perPage);
162
+ return {
163
+ threads: paginated,
164
+ total,
165
+ page,
166
+ perPage: perPageForResponse,
167
+ hasMore: perPageInput === false ? false : offset + perPage < total
168
+ };
169
+ }
170
+ async listMessages(args) {
171
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
172
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
173
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
174
+ throw new error.MastraError(
175
+ {
176
+ id: "CONVEX_STORAGE_LIST_MESSAGES_INVALID_THREAD_ID",
177
+ domain: error.ErrorDomain.STORAGE,
178
+ category: error.ErrorCategory.USER,
179
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
180
+ },
181
+ new Error("threadId must be a non-empty string or array of non-empty strings")
182
+ );
183
+ }
184
+ const perPage = storage.normalizePerPage(perPageInput, 40);
185
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
186
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
187
+ let rows = [];
188
+ for (const tid of threadIds) {
189
+ const threadRows = await this.operations.queryTable(storage.TABLE_MESSAGES, [
190
+ { field: "thread_id", value: tid }
191
+ ]);
192
+ rows.push(...threadRows);
193
+ }
194
+ if (resourceId) {
195
+ rows = rows.filter((row) => row.resourceId === resourceId);
196
+ }
197
+ if (filter?.dateRange) {
198
+ const { start, end } = filter.dateRange;
199
+ rows = rows.filter((row) => {
200
+ const created = new Date(row.createdAt).getTime();
201
+ if (start && created < start.getTime()) return false;
202
+ if (end && created > end.getTime()) return false;
203
+ return true;
204
+ });
205
+ }
206
+ rows.sort((a, b) => {
207
+ const aValue = field === "createdAt" || field === "updatedAt" ? new Date(a[field]).getTime() : a[field];
208
+ const bValue = field === "createdAt" || field === "updatedAt" ? new Date(b[field]).getTime() : b[field];
209
+ if (typeof aValue === "number" && typeof bValue === "number") {
210
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
211
+ }
212
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
213
+ });
214
+ const totalThreadMessages = rows.length;
215
+ const paginatedRows = perPageInput === false ? rows : rows.slice(offset, offset + perPage);
216
+ const messages = paginatedRows.map((row) => this.parseStoredMessage(row));
217
+ const messageIds = new Set(messages.map((msg) => msg.id));
218
+ if (include && include.length > 0) {
219
+ const threadMessagesCache = /* @__PURE__ */ new Map();
220
+ for (const tid of threadIds) {
221
+ const tidRows = rows.filter((r) => r.thread_id === tid);
222
+ threadMessagesCache.set(tid, tidRows);
223
+ }
224
+ for (const includeItem of include) {
225
+ let targetThreadId;
226
+ let target;
227
+ for (const [tid, cachedRows] of threadMessagesCache) {
228
+ target = cachedRows.find((row) => row.id === includeItem.id);
229
+ if (target) {
230
+ targetThreadId = tid;
231
+ break;
232
+ }
233
+ }
234
+ if (!target) {
235
+ const messageRows = await this.operations.queryTable(storage.TABLE_MESSAGES, [
236
+ { field: "id", value: includeItem.id }
237
+ ]);
238
+ if (messageRows.length > 0) {
239
+ target = messageRows[0];
240
+ targetThreadId = target.thread_id;
241
+ if (targetThreadId && !threadMessagesCache.has(targetThreadId)) {
242
+ const otherThreadRows = await this.operations.queryTable(storage.TABLE_MESSAGES, [
243
+ { field: "thread_id", value: targetThreadId }
244
+ ]);
245
+ threadMessagesCache.set(targetThreadId, otherThreadRows);
246
+ }
247
+ }
248
+ }
249
+ if (!target || !targetThreadId) continue;
250
+ if (!messageIds.has(target.id)) {
251
+ messages.push(this.parseStoredMessage(target));
252
+ messageIds.add(target.id);
253
+ }
254
+ const targetThreadRows = threadMessagesCache.get(targetThreadId) || [];
255
+ await this.addContextMessages({
256
+ includeItem,
257
+ allMessages: targetThreadRows,
258
+ targetThreadId,
259
+ messageIds,
260
+ messages
261
+ });
262
+ }
263
+ }
264
+ messages.sort((a, b) => {
265
+ const aValue = field === "createdAt" || field === "updatedAt" ? new Date(a[field]).getTime() : a[field];
266
+ const bValue = field === "createdAt" || field === "updatedAt" ? new Date(b[field]).getTime() : b[field];
267
+ if (typeof aValue === "number" && typeof bValue === "number") {
268
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
269
+ }
270
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
271
+ });
272
+ const hasMore = include && include.length > 0 ? new Set(messages.filter((m) => m.threadId === threadId).map((m) => m.id)).size < totalThreadMessages : perPageInput === false ? false : offset + perPage < totalThreadMessages;
273
+ return {
274
+ messages,
275
+ total: totalThreadMessages,
276
+ page,
277
+ perPage: perPageForResponse,
278
+ hasMore
279
+ };
280
+ }
281
+ async listMessagesById({ messageIds }) {
282
+ if (messageIds.length === 0) {
283
+ return { messages: [] };
284
+ }
285
+ const rows = await this.operations.queryTable(storage.TABLE_MESSAGES, void 0);
286
+ const filtered = rows.filter((row) => messageIds.includes(row.id)).map((row) => this.parseStoredMessage(row));
287
+ const list = new agent.MessageList().add(filtered, "memory");
288
+ return { messages: list.get.all.db() };
289
+ }
290
+ async saveMessages({ messages }) {
291
+ if (messages.length === 0) return { messages: [] };
292
+ const normalized = messages.map((message) => {
293
+ if (!message.threadId) {
294
+ throw new Error("Thread ID is required");
295
+ }
296
+ if (!message.resourceId) {
297
+ throw new Error("Resource ID is required");
298
+ }
299
+ const createdAt = message.createdAt instanceof Date ? message.createdAt.toISOString() : message.createdAt;
300
+ return {
301
+ id: message.id,
302
+ thread_id: message.threadId,
303
+ content: JSON.stringify(message.content),
304
+ role: message.role,
305
+ type: message.type || "v2",
306
+ createdAt,
307
+ resourceId: message.resourceId
308
+ };
309
+ });
310
+ await this.operations.batchInsert({
311
+ tableName: storage.TABLE_MESSAGES,
312
+ records: normalized
313
+ });
314
+ const threadIds = [...new Set(messages.map((m) => m.threadId).filter(Boolean))];
315
+ const now = /* @__PURE__ */ new Date();
316
+ for (const threadId of threadIds) {
317
+ const thread = await this.getThreadById({ threadId });
318
+ if (thread) {
319
+ await this.operations.insert({
320
+ tableName: storage.TABLE_THREADS,
321
+ record: {
322
+ ...thread,
323
+ id: thread.id,
324
+ updatedAt: now.toISOString(),
325
+ createdAt: thread.createdAt instanceof Date ? thread.createdAt.toISOString() : thread.createdAt,
326
+ metadata: thread.metadata ?? {}
327
+ }
328
+ });
329
+ }
330
+ }
331
+ const list = new agent.MessageList().add(messages, "memory");
332
+ return { messages: list.get.all.db() };
333
+ }
334
+ async updateMessages({
335
+ messages
336
+ }) {
337
+ if (messages.length === 0) return [];
338
+ const existing = await this.operations.queryTable(storage.TABLE_MESSAGES, void 0);
339
+ const updated = [];
340
+ const affectedThreadIds = /* @__PURE__ */ new Set();
341
+ for (const update of messages) {
342
+ const current = existing.find((row) => row.id === update.id);
343
+ if (!current) continue;
344
+ affectedThreadIds.add(current.thread_id);
345
+ if (update.threadId) {
346
+ affectedThreadIds.add(update.threadId);
347
+ current.thread_id = update.threadId;
348
+ }
349
+ if (update.resourceId !== void 0) {
350
+ current.resourceId = update.resourceId ?? null;
351
+ }
352
+ if (update.role) {
353
+ current.role = update.role;
354
+ }
355
+ if (update.type) {
356
+ current.type = update.type;
357
+ }
358
+ if (update.content) {
359
+ const existingContent = storage.safelyParseJSON(current.content) || {};
360
+ const mergedContent = {
361
+ ...existingContent,
362
+ ...update.content,
363
+ ...existingContent.metadata && update.content.metadata ? { metadata: { ...existingContent.metadata, ...update.content.metadata } } : {}
364
+ };
365
+ current.content = JSON.stringify(mergedContent);
366
+ }
367
+ await this.operations.insert({
368
+ tableName: storage.TABLE_MESSAGES,
369
+ record: current
370
+ });
371
+ updated.push(this.parseStoredMessage(current));
372
+ }
373
+ const now = /* @__PURE__ */ new Date();
374
+ for (const threadId of affectedThreadIds) {
375
+ const thread = await this.getThreadById({ threadId });
376
+ if (thread) {
377
+ await this.operations.insert({
378
+ tableName: storage.TABLE_THREADS,
379
+ record: {
380
+ ...thread,
381
+ id: thread.id,
382
+ updatedAt: now.toISOString(),
383
+ createdAt: thread.createdAt instanceof Date ? thread.createdAt.toISOString() : thread.createdAt,
384
+ metadata: thread.metadata ?? {}
385
+ }
386
+ });
387
+ }
388
+ }
389
+ return updated;
390
+ }
391
+ async deleteMessages(messageIds) {
392
+ await this.operations.deleteMany(storage.TABLE_MESSAGES, messageIds);
393
+ }
394
+ async saveResource({ resource }) {
395
+ const record = {
396
+ ...resource,
397
+ createdAt: resource.createdAt instanceof Date ? resource.createdAt.toISOString() : resource.createdAt,
398
+ updatedAt: resource.updatedAt instanceof Date ? resource.updatedAt.toISOString() : resource.updatedAt
399
+ };
400
+ if (resource.metadata !== void 0) {
401
+ record.metadata = resource.metadata;
402
+ }
403
+ await this.operations.insert({
404
+ tableName: storage.TABLE_RESOURCES,
405
+ record
406
+ });
407
+ return resource;
408
+ }
409
+ async getResourceById({ resourceId }) {
410
+ const record = await this.operations.load({
411
+ tableName: storage.TABLE_RESOURCES,
412
+ keys: { id: resourceId }
413
+ });
414
+ if (!record) return null;
415
+ return {
416
+ ...record,
417
+ metadata: typeof record.metadata === "string" ? storage.safelyParseJSON(record.metadata) : record.metadata,
418
+ createdAt: new Date(record.createdAt),
419
+ updatedAt: new Date(record.updatedAt)
420
+ };
421
+ }
422
+ async updateResource({
423
+ resourceId,
424
+ workingMemory,
425
+ metadata
426
+ }) {
427
+ const existing = await this.getResourceById({ resourceId });
428
+ const now = /* @__PURE__ */ new Date();
429
+ if (!existing) {
430
+ const created = {
431
+ id: resourceId,
432
+ workingMemory,
433
+ metadata: metadata ?? {},
434
+ createdAt: now,
435
+ updatedAt: now
436
+ };
437
+ return this.saveResource({ resource: created });
438
+ }
439
+ const updated = {
440
+ ...existing,
441
+ workingMemory: workingMemory ?? existing.workingMemory,
442
+ metadata: {
443
+ ...existing.metadata,
444
+ ...metadata
445
+ },
446
+ updatedAt: now
447
+ };
448
+ await this.saveResource({ resource: updated });
449
+ return updated;
450
+ }
451
+ parseStoredMessage(message) {
452
+ const content = storage.safelyParseJSON(message.content);
453
+ return {
454
+ id: message.id,
455
+ threadId: message.thread_id,
456
+ content,
457
+ role: message.role,
458
+ type: message.type,
459
+ createdAt: new Date(message.createdAt),
460
+ resourceId: message.resourceId ?? void 0
461
+ };
462
+ }
463
+ async addContextMessages({
464
+ includeItem,
465
+ allMessages,
466
+ targetThreadId,
467
+ messageIds,
468
+ messages
469
+ }) {
470
+ const ordered = allMessages.filter((row) => row.thread_id === targetThreadId).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
471
+ const targetIndex = ordered.findIndex((row) => row.id === includeItem.id);
472
+ if (targetIndex === -1) return;
473
+ if (includeItem.withPreviousMessages) {
474
+ const start = Math.max(0, targetIndex - includeItem.withPreviousMessages);
475
+ for (let i = start; i < targetIndex; i++) {
476
+ const row = ordered[i];
477
+ if (row && !messageIds.has(row.id)) {
478
+ messages.push(this.parseStoredMessage(row));
479
+ messageIds.add(row.id);
480
+ }
481
+ }
482
+ }
483
+ if (includeItem.withNextMessages) {
484
+ const end = Math.min(ordered.length, targetIndex + includeItem.withNextMessages + 1);
485
+ for (let i = targetIndex + 1; i < end; i++) {
486
+ const row = ordered[i];
487
+ if (row && !messageIds.has(row.id)) {
488
+ messages.push(this.parseStoredMessage(row));
489
+ messageIds.add(row.id);
490
+ }
491
+ }
492
+ }
493
+ }
494
+ };
495
+ var ScoresConvex = class extends storage.ScoresStorage {
496
+ constructor(operations) {
497
+ super();
498
+ this.operations = operations;
499
+ }
500
+ async getScoreById({ id }) {
501
+ const row = await this.operations.load({
502
+ tableName: storage.TABLE_SCORERS,
503
+ keys: { id }
504
+ });
505
+ return row ? this.deserialize(row) : null;
506
+ }
507
+ async saveScore(score) {
508
+ const now = /* @__PURE__ */ new Date();
509
+ const record = {
510
+ ...score,
511
+ id: crypto__default.default.randomUUID(),
512
+ createdAt: now.toISOString(),
513
+ updatedAt: now.toISOString()
514
+ };
515
+ await this.operations.insert({
516
+ tableName: storage.TABLE_SCORERS,
517
+ record
518
+ });
519
+ return { score: this.deserialize(record) };
520
+ }
521
+ async listScoresByScorerId({
522
+ scorerId,
523
+ pagination,
524
+ entityId,
525
+ entityType,
526
+ source
527
+ }) {
528
+ return this.listScores({
529
+ filters: { scorerId, entityId, entityType, source },
530
+ pagination
531
+ });
532
+ }
533
+ async listScoresByRunId({
534
+ runId,
535
+ pagination
536
+ }) {
537
+ return this.listScores({
538
+ filters: { runId },
539
+ pagination
540
+ });
541
+ }
542
+ async listScoresByEntityId({
543
+ entityId,
544
+ entityType,
545
+ pagination
546
+ }) {
547
+ return this.listScores({
548
+ filters: { entityId, entityType },
549
+ pagination
550
+ });
551
+ }
552
+ async listScores({
553
+ filters,
554
+ pagination
555
+ }) {
556
+ if (pagination.page < 0) {
557
+ throw new error.MastraError(
558
+ {
559
+ id: "CONVEX_STORAGE_INVALID_PAGINATION",
560
+ domain: error.ErrorDomain.STORAGE,
561
+ category: error.ErrorCategory.USER
562
+ },
563
+ new Error("page must be >= 0")
564
+ );
565
+ }
566
+ const rows = await this.operations.queryTable(storage.TABLE_SCORERS, void 0);
567
+ const filtered = rows.filter((row) => filters.scorerId ? row.scorerId === filters.scorerId : true).filter((row) => filters.entityId ? row.entityId === filters.entityId : true).filter((row) => filters.entityType ? row.entityType === filters.entityType : true).filter((row) => filters.runId ? row.runId === filters.runId : true).filter((row) => filters.source ? row.source === filters.source : true).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
568
+ const { perPage, page } = pagination;
569
+ const perPageValue = perPage === false ? filtered.length : perPage;
570
+ const start = perPage === false ? 0 : page * perPageValue;
571
+ const end = perPage === false ? filtered.length : start + perPageValue;
572
+ const slice = filtered.slice(start, end).map((row) => this.deserialize(row));
573
+ return {
574
+ pagination: {
575
+ total: filtered.length,
576
+ page,
577
+ perPage,
578
+ hasMore: perPage === false ? false : end < filtered.length
579
+ },
580
+ scores: slice
581
+ };
582
+ }
583
+ deserialize(row) {
584
+ return {
585
+ ...row,
586
+ createdAt: new Date(row.createdAt),
587
+ updatedAt: new Date(row.updatedAt)
588
+ };
589
+ }
590
+ };
591
+ var WorkflowsConvex = class extends storage.WorkflowsStorage {
592
+ constructor(operations) {
593
+ super();
594
+ this.operations = operations;
595
+ }
596
+ async updateWorkflowResults({
597
+ workflowName,
598
+ runId,
599
+ stepId,
600
+ result,
601
+ requestContext
602
+ }) {
603
+ const run = await this.getRun(workflowName, runId);
604
+ if (!run) return {};
605
+ const snapshot = this.ensureSnapshot(run);
606
+ snapshot.context = snapshot.context || {};
607
+ snapshot.context[stepId] = result;
608
+ snapshot.requestContext = { ...snapshot.requestContext || {}, ...requestContext };
609
+ await this.persistWorkflowSnapshot({
610
+ workflowName,
611
+ runId,
612
+ resourceId: run.resourceId,
613
+ snapshot
614
+ });
615
+ return JSON.parse(JSON.stringify(snapshot.context));
616
+ }
617
+ async updateWorkflowState({
618
+ workflowName,
619
+ runId,
620
+ opts
621
+ }) {
622
+ const run = await this.getRun(workflowName, runId);
623
+ if (!run) return void 0;
624
+ const snapshot = this.ensureSnapshot(run);
625
+ const updated = { ...snapshot, ...opts };
626
+ await this.persistWorkflowSnapshot({
627
+ workflowName,
628
+ runId,
629
+ resourceId: run.resourceId,
630
+ snapshot: updated
631
+ });
632
+ return updated;
633
+ }
634
+ async persistWorkflowSnapshot({
635
+ workflowName,
636
+ runId,
637
+ resourceId,
638
+ snapshot
639
+ }) {
640
+ const now = /* @__PURE__ */ new Date();
641
+ const existing = await this.operations.load({
642
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
643
+ keys: { workflow_name: workflowName, run_id: runId }
644
+ });
645
+ await this.operations.insert({
646
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
647
+ record: {
648
+ workflow_name: workflowName,
649
+ run_id: runId,
650
+ resourceId,
651
+ snapshot,
652
+ createdAt: existing?.createdAt ?? now.toISOString(),
653
+ updatedAt: now.toISOString()
654
+ }
655
+ });
656
+ }
657
+ async loadWorkflowSnapshot({
658
+ workflowName,
659
+ runId
660
+ }) {
661
+ const row = await this.operations.load({
662
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
663
+ keys: { workflow_name: workflowName, run_id: runId }
664
+ });
665
+ if (!row) return null;
666
+ return typeof row.snapshot === "string" ? JSON.parse(row.snapshot) : JSON.parse(JSON.stringify(row.snapshot));
667
+ }
668
+ async listWorkflowRuns(args = {}) {
669
+ const { workflowName, fromDate, toDate, perPage, page, resourceId, status } = args;
670
+ let rows = await this.operations.queryTable(storage.TABLE_WORKFLOW_SNAPSHOT, void 0);
671
+ if (workflowName) rows = rows.filter((run) => run.workflow_name === workflowName);
672
+ if (resourceId) rows = rows.filter((run) => run.resourceId === resourceId);
673
+ if (fromDate) rows = rows.filter((run) => new Date(run.createdAt).getTime() >= fromDate.getTime());
674
+ if (toDate) rows = rows.filter((run) => new Date(run.createdAt).getTime() <= toDate.getTime());
675
+ if (status) {
676
+ rows = rows.filter((run) => {
677
+ const snapshot = this.ensureSnapshot(run);
678
+ return snapshot.status === status;
679
+ });
680
+ }
681
+ const total = rows.length;
682
+ rows.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
683
+ if (perPage !== void 0 && page !== void 0) {
684
+ const normalized = storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
685
+ const offset = page * normalized;
686
+ rows = rows.slice(offset, offset + normalized);
687
+ }
688
+ const runs = rows.map((run) => ({
689
+ workflowName: run.workflow_name,
690
+ runId: run.run_id,
691
+ snapshot: this.ensureSnapshot(run),
692
+ createdAt: new Date(run.createdAt),
693
+ updatedAt: new Date(run.updatedAt),
694
+ resourceId: run.resourceId
695
+ }));
696
+ return { runs, total };
697
+ }
698
+ async getWorkflowRunById({
699
+ runId,
700
+ workflowName
701
+ }) {
702
+ const runs = await this.operations.queryTable(storage.TABLE_WORKFLOW_SNAPSHOT, void 0);
703
+ const match = runs.find((run) => run.run_id === runId && (!workflowName || run.workflow_name === workflowName));
704
+ if (!match) return null;
705
+ return {
706
+ workflowName: match.workflow_name,
707
+ runId: match.run_id,
708
+ snapshot: this.ensureSnapshot(match),
709
+ createdAt: new Date(match.createdAt),
710
+ updatedAt: new Date(match.updatedAt),
711
+ resourceId: match.resourceId
712
+ };
713
+ }
714
+ async getRun(workflowName, runId) {
715
+ const runs = await this.operations.queryTable(storage.TABLE_WORKFLOW_SNAPSHOT, [
716
+ { field: "workflow_name", value: workflowName }
717
+ ]);
718
+ return runs.find((run) => run.run_id === runId) ?? null;
719
+ }
720
+ ensureSnapshot(run) {
721
+ if (!run.snapshot) {
722
+ return {
723
+ context: {},
724
+ activePaths: [],
725
+ activeStepsPath: {},
726
+ timestamp: Date.now(),
727
+ suspendedPaths: {},
728
+ resumeLabels: {},
729
+ serializedStepGraph: [],
730
+ value: {},
731
+ waitingPaths: {},
732
+ status: "pending",
733
+ runId: ""
734
+ };
735
+ }
736
+ if (typeof run.snapshot === "string") {
737
+ return JSON.parse(run.snapshot);
738
+ }
739
+ return JSON.parse(JSON.stringify(run.snapshot));
740
+ }
741
+ };
742
+ var StoreOperationsConvex = class extends storage.StoreOperations {
743
+ constructor(client) {
744
+ super();
745
+ this.client = client;
746
+ }
747
+ async hasColumn(_table, _column) {
748
+ return true;
749
+ }
750
+ async createTable(_args) {
751
+ }
752
+ async clearTable({ tableName }) {
753
+ let hasMore = true;
754
+ while (hasMore) {
755
+ const response = await this.client.callStorageRaw({
756
+ op: "clearTable",
757
+ tableName
758
+ });
759
+ hasMore = response.hasMore ?? false;
760
+ }
761
+ }
762
+ async dropTable({ tableName }) {
763
+ let hasMore = true;
764
+ while (hasMore) {
765
+ const response = await this.client.callStorageRaw({
766
+ op: "dropTable",
767
+ tableName
768
+ });
769
+ hasMore = response.hasMore ?? false;
770
+ }
771
+ }
772
+ async alterTable(_args) {
773
+ }
774
+ async insert({ tableName, record }) {
775
+ await this.client.callStorage({
776
+ op: "insert",
777
+ tableName,
778
+ record: this.normalizeRecord(tableName, record)
779
+ });
780
+ }
781
+ async batchInsert({ tableName, records }) {
782
+ if (records.length === 0) return;
783
+ await this.client.callStorage({
784
+ op: "batchInsert",
785
+ tableName,
786
+ records: records.map((record) => this.normalizeRecord(tableName, record))
787
+ });
788
+ }
789
+ async load({ tableName, keys }) {
790
+ const result = await this.client.callStorage({
791
+ op: "load",
792
+ tableName,
793
+ keys
794
+ });
795
+ return result;
796
+ }
797
+ async queryTable(tableName, filters) {
798
+ return this.client.callStorage({
799
+ op: "queryTable",
800
+ tableName,
801
+ filters
802
+ });
803
+ }
804
+ async deleteMany(tableName, ids) {
805
+ if (ids.length === 0) return;
806
+ await this.client.callStorage({
807
+ op: "deleteMany",
808
+ tableName,
809
+ ids
810
+ });
811
+ }
812
+ normalizeRecord(tableName, record) {
813
+ const normalized = { ...record };
814
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT && !normalized.id) {
815
+ const runId = normalized.run_id || normalized.runId;
816
+ const workflowName = normalized.workflow_name || normalized.workflowName;
817
+ normalized.id = workflowName ? `${workflowName}-${runId}` : runId;
818
+ }
819
+ if (!normalized.id) {
820
+ normalized.id = crypto__default.default.randomUUID();
821
+ }
822
+ for (const [key, value] of Object.entries(normalized)) {
823
+ if (value instanceof Date) {
824
+ normalized[key] = value.toISOString();
825
+ }
826
+ }
827
+ return normalized;
828
+ }
829
+ };
830
+
831
+ // src/storage/index.ts
832
+ var ConvexStore = class extends storage.MastraStorage {
833
+ operations;
834
+ memory;
835
+ workflows;
836
+ scores;
837
+ constructor(config) {
838
+ super({ id: config.id, name: config.name ?? "ConvexStore" });
839
+ const client = new ConvexAdminClient(config);
840
+ this.operations = new StoreOperationsConvex(client);
841
+ this.memory = new MemoryConvex(this.operations);
842
+ this.workflows = new WorkflowsConvex(this.operations);
843
+ this.scores = new ScoresConvex(this.operations);
844
+ this.stores = {
845
+ operations: this.operations,
846
+ memory: this.memory,
847
+ workflows: this.workflows,
848
+ scores: this.scores
849
+ };
850
+ }
851
+ get supports() {
852
+ return {
853
+ selectByIncludeResourceScope: true,
854
+ resourceWorkingMemory: true,
855
+ hasColumn: false,
856
+ createTable: false,
857
+ deleteMessages: true,
858
+ observabilityInstance: false,
859
+ listScoresBySpan: false
860
+ };
861
+ }
862
+ async createTable(_args) {
863
+ }
864
+ async clearTable({ tableName }) {
865
+ await this.operations.clearTable({ tableName });
866
+ }
867
+ async dropTable({ tableName }) {
868
+ await this.operations.dropTable({ tableName });
869
+ }
870
+ async alterTable(_args) {
871
+ }
872
+ async insert({ tableName, record }) {
873
+ await this.operations.insert({ tableName, record });
874
+ }
875
+ async batchInsert({ tableName, records }) {
876
+ await this.operations.batchInsert({ tableName, records });
877
+ }
878
+ async load({ tableName, keys }) {
879
+ return this.operations.load({ tableName, keys });
880
+ }
881
+ async getThreadById({ threadId }) {
882
+ return this.memory.getThreadById({ threadId });
883
+ }
884
+ async saveThread({ thread }) {
885
+ return this.memory.saveThread({ thread });
886
+ }
887
+ async updateThread({
888
+ id,
889
+ title,
890
+ metadata
891
+ }) {
892
+ return this.memory.updateThread({ id, title, metadata });
893
+ }
894
+ async deleteThread({ threadId }) {
895
+ await this.memory.deleteThread({ threadId });
896
+ }
897
+ async listMessages(args) {
898
+ return this.memory.listMessages(args);
899
+ }
900
+ async listMessagesById({ messageIds }) {
901
+ return this.memory.listMessagesById({ messageIds });
902
+ }
903
+ async saveMessages(args) {
904
+ return this.memory.saveMessages(args);
905
+ }
906
+ async updateMessages({
907
+ messages
908
+ }) {
909
+ return this.memory.updateMessages({ messages });
910
+ }
911
+ async deleteMessages(messageIds) {
912
+ await this.memory.deleteMessages(messageIds);
913
+ }
914
+ async listThreadsByResourceId(args) {
915
+ return this.memory.listThreadsByResourceId(args);
916
+ }
917
+ async getResourceById({ resourceId }) {
918
+ return this.memory.getResourceById({ resourceId });
919
+ }
920
+ async saveResource({ resource }) {
921
+ return this.memory.saveResource({ resource });
922
+ }
923
+ async updateResource({
924
+ resourceId,
925
+ workingMemory,
926
+ metadata
927
+ }) {
928
+ return this.memory.updateResource({ resourceId, workingMemory, metadata });
929
+ }
930
+ async updateWorkflowResults(params) {
931
+ return this.workflows.updateWorkflowResults(params);
932
+ }
933
+ async updateWorkflowState(params) {
934
+ return this.workflows.updateWorkflowState(params);
935
+ }
936
+ async persistWorkflowSnapshot({
937
+ workflowName,
938
+ runId,
939
+ resourceId,
940
+ snapshot
941
+ }) {
942
+ await this.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
943
+ }
944
+ async loadWorkflowSnapshot({
945
+ workflowName,
946
+ runId
947
+ }) {
948
+ return this.workflows.loadWorkflowSnapshot({ workflowName, runId });
949
+ }
950
+ async listWorkflowRuns(args) {
951
+ return this.workflows.listWorkflowRuns(args);
952
+ }
953
+ async getWorkflowRunById({
954
+ runId,
955
+ workflowName
956
+ }) {
957
+ return this.workflows.getWorkflowRunById({ runId, workflowName });
958
+ }
959
+ async getScoreById({ id }) {
960
+ return this.scores.getScoreById({ id });
961
+ }
962
+ async saveScore(score) {
963
+ return this.scores.saveScore(score);
964
+ }
965
+ async listScoresByScorerId({
966
+ scorerId,
967
+ pagination,
968
+ entityId,
969
+ entityType,
970
+ source
971
+ }) {
972
+ return this.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
973
+ }
974
+ async listScoresByRunId({
975
+ runId,
976
+ pagination
977
+ }) {
978
+ return this.scores.listScoresByRunId({ runId, pagination });
979
+ }
980
+ async listScoresByEntityId({
981
+ entityId,
982
+ entityType,
983
+ pagination
984
+ }) {
985
+ return this.scores.listScoresByEntityId({ entityId, entityType, pagination });
986
+ }
987
+ };
988
+ var INDEX_METADATA_TABLE = "mastra_vector_indexes";
989
+ var ConvexVector = class extends vector.MastraVector {
990
+ client;
991
+ constructor(config) {
992
+ super({ id: config.id });
993
+ this.client = new ConvexAdminClient(config);
994
+ }
995
+ async createIndex({ indexName, dimension }) {
996
+ await this.callStorage({
997
+ op: "insert",
998
+ tableName: INDEX_METADATA_TABLE,
999
+ record: {
1000
+ id: indexName,
1001
+ indexName,
1002
+ dimension,
1003
+ metric: "cosine",
1004
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1005
+ }
1006
+ });
1007
+ }
1008
+ async deleteIndex({ indexName }) {
1009
+ await this.callStorage({
1010
+ op: "deleteMany",
1011
+ tableName: INDEX_METADATA_TABLE,
1012
+ ids: [indexName]
1013
+ });
1014
+ await this.callStorageUntilComplete({
1015
+ op: "clearTable",
1016
+ tableName: this.vectorTable(indexName)
1017
+ });
1018
+ }
1019
+ async truncateIndex({ indexName }) {
1020
+ await this.callStorageUntilComplete({
1021
+ op: "clearTable",
1022
+ tableName: this.vectorTable(indexName)
1023
+ });
1024
+ }
1025
+ async listIndexes() {
1026
+ const indexes = await this.callStorage({
1027
+ op: "queryTable",
1028
+ tableName: INDEX_METADATA_TABLE
1029
+ });
1030
+ return indexes.map((index) => index.id);
1031
+ }
1032
+ async describeIndex({ indexName }) {
1033
+ const index = await this.callStorage({
1034
+ op: "load",
1035
+ tableName: INDEX_METADATA_TABLE,
1036
+ keys: { id: indexName }
1037
+ });
1038
+ if (!index) {
1039
+ throw new Error(`Index ${indexName} not found`);
1040
+ }
1041
+ const vectors = await this.callStorage({
1042
+ op: "queryTable",
1043
+ tableName: this.vectorTable(indexName)
1044
+ });
1045
+ return {
1046
+ dimension: index.dimension,
1047
+ count: vectors.length,
1048
+ metric: "cosine"
1049
+ };
1050
+ }
1051
+ async upsert({ indexName, vectors, ids, metadata }) {
1052
+ const vectorIds = ids ?? vectors.map(() => crypto__default.default.randomUUID());
1053
+ const records = vectors.map((vector, i) => ({
1054
+ id: vectorIds[i],
1055
+ embedding: vector,
1056
+ metadata: metadata?.[i]
1057
+ }));
1058
+ await this.callStorage({
1059
+ op: "batchInsert",
1060
+ tableName: this.vectorTable(indexName),
1061
+ records
1062
+ });
1063
+ return vectorIds;
1064
+ }
1065
+ async query({
1066
+ indexName,
1067
+ queryVector,
1068
+ topK = 10,
1069
+ includeVector = false,
1070
+ filter
1071
+ }) {
1072
+ const vectors = await this.callStorage({
1073
+ op: "queryTable",
1074
+ tableName: this.vectorTable(indexName)
1075
+ });
1076
+ const filtered = filter && !this.isEmptyFilter(filter) ? vectors.filter((record) => this.matchesFilter(record.metadata, filter)) : vectors;
1077
+ const scored = filtered.map((record) => ({
1078
+ id: record.id,
1079
+ score: cosineSimilarity(queryVector, record.embedding),
1080
+ metadata: record.metadata,
1081
+ ...includeVector ? { vector: record.embedding } : {}
1082
+ })).filter((result) => Number.isFinite(result.score)).sort((a, b) => b.score - a.score).slice(0, topK);
1083
+ return scored;
1084
+ }
1085
+ async updateVector(params) {
1086
+ const hasId = "id" in params && params.id;
1087
+ const hasFilter = "filter" in params && params.filter !== void 0;
1088
+ if (hasId && hasFilter) {
1089
+ throw new Error("ConvexVector.updateVector: id and filter are mutually exclusive");
1090
+ }
1091
+ if (hasFilter) {
1092
+ const filter = params.filter;
1093
+ if (this.isEmptyFilter(filter)) {
1094
+ throw new Error("ConvexVector.updateVector: cannot update with empty filter");
1095
+ }
1096
+ const vectors = await this.callStorage({
1097
+ op: "queryTable",
1098
+ tableName: this.vectorTable(params.indexName)
1099
+ });
1100
+ const matching = vectors.filter((record) => this.matchesFilter(record.metadata, filter));
1101
+ for (const existing2 of matching) {
1102
+ const updated2 = {
1103
+ ...existing2,
1104
+ ...params.update.vector ? { embedding: params.update.vector } : {},
1105
+ ...params.update.metadata ? { metadata: { ...existing2.metadata, ...params.update.metadata } } : {}
1106
+ };
1107
+ await this.callStorage({
1108
+ op: "insert",
1109
+ tableName: this.vectorTable(params.indexName),
1110
+ record: updated2
1111
+ });
1112
+ }
1113
+ return;
1114
+ }
1115
+ if (!hasId) {
1116
+ throw new Error("ConvexVector.updateVector: Either id or filter must be provided");
1117
+ }
1118
+ const existing = await this.callStorage({
1119
+ op: "load",
1120
+ tableName: this.vectorTable(params.indexName),
1121
+ keys: { id: params.id }
1122
+ });
1123
+ if (!existing) return;
1124
+ const updated = {
1125
+ ...existing,
1126
+ ...params.update.vector ? { embedding: params.update.vector } : {},
1127
+ ...params.update.metadata ? { metadata: { ...existing.metadata, ...params.update.metadata } } : {}
1128
+ };
1129
+ await this.callStorage({
1130
+ op: "insert",
1131
+ tableName: this.vectorTable(params.indexName),
1132
+ record: updated
1133
+ });
1134
+ }
1135
+ async deleteVector({ indexName, id }) {
1136
+ await this.callStorage({
1137
+ op: "deleteMany",
1138
+ tableName: this.vectorTable(indexName),
1139
+ ids: [id]
1140
+ });
1141
+ }
1142
+ async deleteVectors(params) {
1143
+ const { indexName } = params;
1144
+ const hasIds = "ids" in params && params.ids !== void 0;
1145
+ const hasFilter = "filter" in params && params.filter !== void 0;
1146
+ if (hasIds && hasFilter) {
1147
+ throw new Error("ConvexVector.deleteVectors: ids and filter are mutually exclusive");
1148
+ }
1149
+ if (!hasIds && !hasFilter) {
1150
+ throw new Error("ConvexVector.deleteVectors: Either filter or ids must be provided");
1151
+ }
1152
+ if (hasIds) {
1153
+ const ids = params.ids;
1154
+ if (ids.length === 0) {
1155
+ throw new Error("ConvexVector.deleteVectors: cannot delete with empty ids array");
1156
+ }
1157
+ await this.callStorage({
1158
+ op: "deleteMany",
1159
+ tableName: this.vectorTable(indexName),
1160
+ ids
1161
+ });
1162
+ return;
1163
+ }
1164
+ const filter = params.filter;
1165
+ if (this.isEmptyFilter(filter)) {
1166
+ throw new Error("ConvexVector.deleteVectors: cannot delete with empty filter");
1167
+ }
1168
+ const vectors = await this.callStorage({
1169
+ op: "queryTable",
1170
+ tableName: this.vectorTable(indexName)
1171
+ });
1172
+ const matchingIds = vectors.filter((record) => this.matchesFilter(record.metadata, filter)).map((record) => record.id);
1173
+ if (matchingIds.length > 0) {
1174
+ await this.callStorage({
1175
+ op: "deleteMany",
1176
+ tableName: this.vectorTable(indexName),
1177
+ ids: matchingIds
1178
+ });
1179
+ }
1180
+ }
1181
+ vectorTable(indexName) {
1182
+ return `mastra_vector_${indexName}`;
1183
+ }
1184
+ isEmptyFilter(filter) {
1185
+ if (!filter) return true;
1186
+ return Object.keys(filter).length === 0;
1187
+ }
1188
+ matchesFilter(recordMetadata, filter) {
1189
+ if (!recordMetadata) return false;
1190
+ if (!filter || Object.keys(filter).length === 0) return true;
1191
+ if ("metadata" in filter && filter.metadata) {
1192
+ return this.matchesFilterConditions(recordMetadata, filter.metadata);
1193
+ }
1194
+ return this.matchesFilterConditions(recordMetadata, filter);
1195
+ }
1196
+ matchesFilterConditions(recordMetadata, conditions) {
1197
+ for (const [key, value] of Object.entries(conditions)) {
1198
+ if (key === "$and" && Array.isArray(value)) {
1199
+ const allMatch = value.every((cond) => this.matchesFilterConditions(recordMetadata, cond));
1200
+ if (!allMatch) return false;
1201
+ continue;
1202
+ }
1203
+ if (key === "$or" && Array.isArray(value)) {
1204
+ const anyMatch = value.some((cond) => this.matchesFilterConditions(recordMetadata, cond));
1205
+ if (!anyMatch) return false;
1206
+ continue;
1207
+ }
1208
+ if (typeof value === "object" && value !== null && "$in" in value) {
1209
+ if (!Array.isArray(value.$in) || !value.$in.includes(recordMetadata[key])) {
1210
+ return false;
1211
+ }
1212
+ continue;
1213
+ }
1214
+ if (typeof value === "object" && value !== null && "$nin" in value) {
1215
+ if (Array.isArray(value.$nin) && value.$nin.includes(recordMetadata[key])) {
1216
+ return false;
1217
+ }
1218
+ continue;
1219
+ }
1220
+ if (typeof value === "object" && value !== null && "$gt" in value) {
1221
+ if (!(recordMetadata[key] > value.$gt)) {
1222
+ return false;
1223
+ }
1224
+ continue;
1225
+ }
1226
+ if (typeof value === "object" && value !== null && "$gte" in value) {
1227
+ if (!(recordMetadata[key] >= value.$gte)) {
1228
+ return false;
1229
+ }
1230
+ continue;
1231
+ }
1232
+ if (typeof value === "object" && value !== null && "$lt" in value) {
1233
+ if (!(recordMetadata[key] < value.$lt)) {
1234
+ return false;
1235
+ }
1236
+ continue;
1237
+ }
1238
+ if (typeof value === "object" && value !== null && "$lte" in value) {
1239
+ if (!(recordMetadata[key] <= value.$lte)) {
1240
+ return false;
1241
+ }
1242
+ continue;
1243
+ }
1244
+ if (typeof value === "object" && value !== null && "$ne" in value) {
1245
+ if (recordMetadata[key] === value.$ne) {
1246
+ return false;
1247
+ }
1248
+ continue;
1249
+ }
1250
+ if (recordMetadata[key] !== value) {
1251
+ return false;
1252
+ }
1253
+ }
1254
+ return true;
1255
+ }
1256
+ async callStorage(request) {
1257
+ return this.client.callStorage(request);
1258
+ }
1259
+ /**
1260
+ * Call storage repeatedly until hasMore is false.
1261
+ * Use for bulk operations like clearTable that may need multiple batches.
1262
+ */
1263
+ async callStorageUntilComplete(request) {
1264
+ let hasMore = true;
1265
+ while (hasMore) {
1266
+ const response = await this.client.callStorageRaw(request);
1267
+ hasMore = response.hasMore ?? false;
1268
+ }
1269
+ }
1270
+ };
1271
+ function cosineSimilarity(a, b) {
1272
+ if (a.length !== b.length) {
1273
+ return -1;
1274
+ }
1275
+ let dot = 0;
1276
+ let magA = 0;
1277
+ let magB = 0;
1278
+ for (let i = 0; i < a.length; i++) {
1279
+ const aVal = a[i] ?? 0;
1280
+ const bVal = b[i] ?? 0;
1281
+ dot += aVal * bVal;
1282
+ magA += aVal * aVal;
1283
+ magB += bVal * bVal;
1284
+ }
1285
+ if (magA === 0 || magB === 0) {
1286
+ return -1;
1287
+ }
1288
+ return dot / (Math.sqrt(magA) * Math.sqrt(magB));
1289
+ }
1290
+
1291
+ Object.defineProperty(exports, "TABLE_MESSAGES", {
1292
+ enumerable: true,
1293
+ get: function () { return chunkQKN2PWR2_cjs.TABLE_MESSAGES; }
1294
+ });
1295
+ Object.defineProperty(exports, "TABLE_RESOURCES", {
1296
+ enumerable: true,
1297
+ get: function () { return chunkQKN2PWR2_cjs.TABLE_RESOURCES; }
1298
+ });
1299
+ Object.defineProperty(exports, "TABLE_SCORERS", {
1300
+ enumerable: true,
1301
+ get: function () { return chunkQKN2PWR2_cjs.TABLE_SCORERS; }
1302
+ });
1303
+ Object.defineProperty(exports, "TABLE_THREADS", {
1304
+ enumerable: true,
1305
+ get: function () { return chunkQKN2PWR2_cjs.TABLE_THREADS; }
1306
+ });
1307
+ Object.defineProperty(exports, "TABLE_WORKFLOW_SNAPSHOT", {
1308
+ enumerable: true,
1309
+ get: function () { return chunkQKN2PWR2_cjs.TABLE_WORKFLOW_SNAPSHOT; }
1310
+ });
1311
+ Object.defineProperty(exports, "mastraDocumentsTable", {
1312
+ enumerable: true,
1313
+ get: function () { return chunkQKN2PWR2_cjs.mastraDocumentsTable; }
1314
+ });
1315
+ Object.defineProperty(exports, "mastraMessagesTable", {
1316
+ enumerable: true,
1317
+ get: function () { return chunkQKN2PWR2_cjs.mastraMessagesTable; }
1318
+ });
1319
+ Object.defineProperty(exports, "mastraResourcesTable", {
1320
+ enumerable: true,
1321
+ get: function () { return chunkQKN2PWR2_cjs.mastraResourcesTable; }
1322
+ });
1323
+ Object.defineProperty(exports, "mastraScoresTable", {
1324
+ enumerable: true,
1325
+ get: function () { return chunkQKN2PWR2_cjs.mastraScoresTable; }
1326
+ });
1327
+ Object.defineProperty(exports, "mastraStorage", {
1328
+ enumerable: true,
1329
+ get: function () { return chunkQKN2PWR2_cjs.mastraStorage; }
1330
+ });
1331
+ Object.defineProperty(exports, "mastraThreadsTable", {
1332
+ enumerable: true,
1333
+ get: function () { return chunkQKN2PWR2_cjs.mastraThreadsTable; }
1334
+ });
1335
+ Object.defineProperty(exports, "mastraVectorIndexesTable", {
1336
+ enumerable: true,
1337
+ get: function () { return chunkQKN2PWR2_cjs.mastraVectorIndexesTable; }
1338
+ });
1339
+ Object.defineProperty(exports, "mastraVectorsTable", {
1340
+ enumerable: true,
1341
+ get: function () { return chunkQKN2PWR2_cjs.mastraVectorsTable; }
1342
+ });
1343
+ Object.defineProperty(exports, "mastraWorkflowSnapshotsTable", {
1344
+ enumerable: true,
1345
+ get: function () { return chunkQKN2PWR2_cjs.mastraWorkflowSnapshotsTable; }
1346
+ });
1347
+ exports.ConvexStore = ConvexStore;
1348
+ exports.ConvexVector = ConvexVector;
1349
+ //# sourceMappingURL=index.cjs.map
1350
+ //# sourceMappingURL=index.cjs.map