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