@mastra/convex 0.0.0-new-button-export-20251219133013 → 0.0.0-salesman-20260127182805

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.
@@ -0,0 +1,240 @@
1
+ # Vectors API Reference
2
+
3
+ > API reference for vectors - 1 entries
4
+
5
+
6
+ ---
7
+
8
+ ## Reference: Convex Vector Store
9
+
10
+ > Documentation for the ConvexVector class in Mastra, which provides vector search using Convex.
11
+
12
+ The ConvexVector class provides vector storage and similarity search using [Convex](https://convex.dev). It stores embeddings inside Convex and performs cosine similarity search.
13
+
14
+ ## Installation
15
+
16
+ ```bash npm2yarn
17
+ npm install @mastra/convex@latest
18
+ ```
19
+
20
+ ## Convex Setup
21
+
22
+ Before using `ConvexVector`, you need to set up the Convex schema and storage handler. See [Convex Storage Setup](../storage/convex#convex-setup) for setup instructions.
23
+
24
+ ## Constructor Options
25
+
26
+ ## Constructor Examples
27
+
28
+ ### Basic Configuration
29
+
30
+ ```ts
31
+ import { ConvexVector } from "@mastra/convex";
32
+
33
+ const vectorStore = new ConvexVector({
34
+ id: 'convex-vectors',
35
+ deploymentUrl: "https://your-project.convex.cloud",
36
+ adminAuthToken: "your-admin-token",
37
+ });
38
+ ```
39
+
40
+ ### Custom Storage Function
41
+
42
+ ```ts
43
+ const vectorStore = new ConvexVector({
44
+ id: 'convex-vectors',
45
+ deploymentUrl: "https://your-project.convex.cloud",
46
+ adminAuthToken: "your-admin-token",
47
+ storageFunction: "custom/path:handler",
48
+ });
49
+ ```
50
+
51
+ ## Methods
52
+
53
+ ### createIndex()
54
+
55
+ ```typescript
56
+ await vectorStore.createIndex({
57
+ indexName: "my_vectors",
58
+ dimension: 1536,
59
+ });
60
+ ```
61
+
62
+ ### upsert()
63
+
64
+ ```typescript
65
+ await vectorStore.upsert({
66
+ indexName: "my_vectors",
67
+ vectors: [[0.1, 0.2, 0.3, ...]],
68
+ metadata: [{ label: "example" }],
69
+ ids: ["vec-1"],
70
+ });
71
+ ```
72
+
73
+ ### query()
74
+
75
+ ```typescript
76
+ const results = await vectorStore.query({
77
+ indexName: "my_vectors",
78
+ queryVector: [0.1, 0.2, 0.3, ...],
79
+ topK: 5,
80
+ filter: { category: "documents" },
81
+ });
82
+ ```
83
+
84
+ ### listIndexes()
85
+
86
+ Returns an array of index names as strings.
87
+
88
+ ```typescript
89
+ const indexes = await vectorStore.listIndexes();
90
+ // ["my_vectors", "embeddings", ...]
91
+ ```
92
+
93
+ ### describeIndex()
94
+
95
+ Returns:
96
+
97
+ ```typescript
98
+ interface IndexStats {
99
+ dimension: number;
100
+ count: number;
101
+ metric: "cosine" | "euclidean" | "dotproduct";
102
+ }
103
+ ```
104
+
105
+ ### deleteIndex()
106
+
107
+ Deletes the index and all its vectors.
108
+
109
+ ```typescript
110
+ await vectorStore.deleteIndex({ indexName: "my_vectors" });
111
+ ```
112
+
113
+ ### updateVector()
114
+
115
+ Update a single vector by ID or by metadata filter. Either `id` or `filter` must be provided, but not both.
116
+
117
+ ```typescript
118
+ // Update by ID
119
+ await vectorStore.updateVector({
120
+ indexName: "my_vectors",
121
+ id: "vector123",
122
+ update: {
123
+ vector: [0.1, 0.2, 0.3],
124
+ metadata: { label: "updated" },
125
+ },
126
+ });
127
+
128
+ // Update by filter
129
+ await vectorStore.updateVector({
130
+ indexName: "my_vectors",
131
+ filter: { category: "product" },
132
+ update: {
133
+ metadata: { status: "reviewed" },
134
+ },
135
+ });
136
+ ```
137
+
138
+ ### deleteVector()
139
+
140
+ ```typescript
141
+ await vectorStore.deleteVector({ indexName: "my_vectors", id: "vector123" });
142
+ ```
143
+
144
+ ### deleteVectors()
145
+
146
+ Delete multiple vectors by IDs or by metadata filter. Either `ids` or `filter` must be provided, but not both.
147
+
148
+ ```typescript
149
+ // Delete by IDs
150
+ await vectorStore.deleteVectors({
151
+ indexName: "my_vectors",
152
+ ids: ["vec1", "vec2", "vec3"],
153
+ });
154
+
155
+ // Delete by filter
156
+ await vectorStore.deleteVectors({
157
+ indexName: "my_vectors",
158
+ filter: { status: "archived" },
159
+ });
160
+ ```
161
+
162
+ ## Response Types
163
+
164
+ Query results are returned in this format:
165
+
166
+ ```typescript
167
+ interface QueryResult {
168
+ id: string;
169
+ score: number;
170
+ metadata: Record<string, any>;
171
+ vector?: number[]; // Only included if includeVector is true
172
+ }
173
+ ```
174
+
175
+ ## Metadata Filtering
176
+
177
+ ConvexVector supports metadata filtering with various operators:
178
+
179
+ ```typescript
180
+ // Simple equality
181
+ const results = await vectorStore.query({
182
+ indexName: "my_vectors",
183
+ queryVector: embedding,
184
+ filter: { category: "documents" },
185
+ });
186
+
187
+ // Comparison operators
188
+ const results = await vectorStore.query({
189
+ indexName: "my_vectors",
190
+ queryVector: embedding,
191
+ filter: {
192
+ price: { $gt: 100 },
193
+ status: { $in: ["active", "pending"] },
194
+ },
195
+ });
196
+
197
+ // Logical operators
198
+ const results = await vectorStore.query({
199
+ indexName: "my_vectors",
200
+ queryVector: embedding,
201
+ filter: {
202
+ $and: [
203
+ { category: "electronics" },
204
+ { price: { $lte: 500 } },
205
+ ],
206
+ },
207
+ });
208
+ ```
209
+
210
+ ### Supported Filter Operators
211
+
212
+ | Operator | Description |
213
+ | -------- | ----------- |
214
+ | `$eq` | Equal to |
215
+ | `$ne` | Not equal to |
216
+ | `$gt` | Greater than |
217
+ | `$gte` | Greater than or equal |
218
+ | `$lt` | Less than |
219
+ | `$lte` | Less than or equal |
220
+ | `$in` | In array |
221
+ | `$nin` | Not in array |
222
+ | `$and` | Logical AND |
223
+ | `$or` | Logical OR |
224
+
225
+ ## Architecture
226
+
227
+ ConvexVector stores vectors in the `mastra_vectors` table with the following structure:
228
+
229
+ - `id`: Unique vector identifier
230
+ - `indexName`: Name of the index
231
+ - `embedding`: The vector data (array of floats)
232
+ - `metadata`: Optional JSON metadata
233
+
234
+ Vector similarity search is performed using cosine similarity, computed in the Convex function.
235
+
236
+ ## Related
237
+
238
+ - [Convex Storage](../storage/convex)
239
+ - [Metadata Filters](../rag/metadata-filters)
240
+ - [Convex Documentation](https://docs.convex.dev/)
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkBKVR7SL7_cjs = require('./chunk-BKVR7SL7.cjs');
4
- var chunkZBUP3DS6_cjs = require('./chunk-ZBUP3DS6.cjs');
4
+ var chunkFTVDAP6U_cjs = require('./chunk-FTVDAP6U.cjs');
5
5
  var storage = require('@mastra/core/storage');
6
6
  var agent = require('@mastra/core/agent');
7
7
  var error = require('@mastra/core/error');
@@ -90,6 +90,19 @@ var ConvexDB = class extends base.MastraBase {
90
90
  async hasColumn(_table, _column) {
91
91
  return true;
92
92
  }
93
+ async createTable({
94
+ tableName,
95
+ schema: _schema
96
+ }) {
97
+ this.logger.debug(`ConvexDB: createTable called for ${tableName} (schema managed server-side)`);
98
+ }
99
+ async alterTable({
100
+ tableName,
101
+ schema: _schema,
102
+ ifNotExists: _ifNotExists
103
+ }) {
104
+ this.logger.debug(`ConvexDB: alterTable called for ${tableName} (schema managed server-side)`);
105
+ }
93
106
  async clearTable({ tableName }) {
94
107
  let hasMore = true;
95
108
  while (hasMore) {
@@ -241,18 +254,41 @@ var MemoryConvex = class extends storage.MemoryStorage {
241
254
  );
242
255
  await this.#db.deleteMany(storage.TABLE_THREADS, [threadId]);
243
256
  }
244
- async listThreadsByResourceId(args) {
245
- const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
257
+ async listThreads(args) {
258
+ const { page = 0, perPage: perPageInput, orderBy, filter } = args;
259
+ try {
260
+ this.validatePaginationInput(page, perPageInput ?? 100);
261
+ } catch (error$1) {
262
+ throw new error.MastraError(
263
+ {
264
+ id: storage.createStorageErrorId("CONVEX", "LIST_THREADS", "INVALID_PAGE"),
265
+ domain: error.ErrorDomain.STORAGE,
266
+ category: error.ErrorCategory.USER,
267
+ details: { page, ...perPageInput !== void 0 && { perPage: perPageInput } }
268
+ },
269
+ error$1 instanceof Error ? error$1 : new Error("Invalid pagination parameters")
270
+ );
271
+ }
246
272
  const perPage = storage.normalizePerPage(perPageInput, 100);
247
273
  const { field, direction } = this.parseOrderBy(orderBy);
248
274
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
249
- const rows = await this.#db.queryTable(storage.TABLE_THREADS, [{ field: "resourceId", value: resourceId }]);
250
- const threads = rows.map((row) => ({
275
+ const queryFilters = [];
276
+ if (filter?.resourceId) {
277
+ queryFilters.push({ field: "resourceId", value: filter.resourceId });
278
+ }
279
+ const rows = await this.#db.queryTable(storage.TABLE_THREADS, queryFilters);
280
+ let threads = rows.map((row) => ({
251
281
  ...row,
252
282
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata,
253
283
  createdAt: new Date(row.createdAt),
254
284
  updatedAt: new Date(row.updatedAt)
255
285
  }));
286
+ if (filter?.metadata && Object.keys(filter.metadata).length > 0) {
287
+ threads = threads.filter((thread) => {
288
+ if (!thread.metadata) return false;
289
+ return Object.entries(filter.metadata).every(([key, value]) => thread.metadata[key] === value);
290
+ });
291
+ }
256
292
  threads.sort((a, b) => {
257
293
  const aValue = a[field];
258
294
  const bValue = b[field];
@@ -295,15 +331,7 @@ var MemoryConvex = class extends storage.MemoryStorage {
295
331
  if (resourceId) {
296
332
  rows = rows.filter((row) => row.resourceId === resourceId);
297
333
  }
298
- if (filter?.dateRange) {
299
- const { start, end } = filter.dateRange;
300
- rows = rows.filter((row) => {
301
- const created = new Date(row.createdAt).getTime();
302
- if (start && created < start.getTime()) return false;
303
- if (end && created > end.getTime()) return false;
304
- return true;
305
- });
306
- }
334
+ rows = storage.filterByDateRange(rows, (row) => new Date(row.createdAt), filter?.dateRange);
307
335
  rows.sort((a, b) => {
308
336
  const aValue = field === "createdAt" || field === "updatedAt" ? new Date(a[field]).getTime() : a[field];
309
337
  const bValue = field === "createdAt" || field === "updatedAt" ? new Date(b[field]).getTime() : b[field];
@@ -859,143 +887,23 @@ var WorkflowsConvex = class extends storage.WorkflowsStorage {
859
887
  };
860
888
 
861
889
  // src/storage/index.ts
862
- var ConvexStore = class extends storage.MastraStorage {
863
- memory;
864
- workflows;
865
- scores;
890
+ var isClientConfig = (config) => {
891
+ return "client" in config;
892
+ };
893
+ var ConvexStore = class extends storage.MastraCompositeStore {
866
894
  constructor(config) {
867
895
  super({ id: config.id, name: config.name ?? "ConvexStore", disableInit: config.disableInit });
868
- const client = new ConvexAdminClient(config);
896
+ const client = isClientConfig(config) ? config.client : new ConvexAdminClient(config);
869
897
  const domainConfig = { client };
870
- this.memory = new MemoryConvex(domainConfig);
871
- this.workflows = new WorkflowsConvex(domainConfig);
872
- this.scores = new ScoresConvex(domainConfig);
898
+ const memory = new MemoryConvex(domainConfig);
899
+ const workflows = new WorkflowsConvex(domainConfig);
900
+ const scores = new ScoresConvex(domainConfig);
873
901
  this.stores = {
874
- memory: this.memory,
875
- workflows: this.workflows,
876
- scores: this.scores
877
- };
878
- }
879
- get supports() {
880
- return {
881
- selectByIncludeResourceScope: true,
882
- resourceWorkingMemory: true,
883
- hasColumn: false,
884
- createTable: false,
885
- deleteMessages: true,
886
- observabilityInstance: false,
887
- listScoresBySpan: false
902
+ memory,
903
+ workflows,
904
+ scores
888
905
  };
889
906
  }
890
- async getThreadById({ threadId }) {
891
- return this.memory.getThreadById({ threadId });
892
- }
893
- async saveThread({ thread }) {
894
- return this.memory.saveThread({ thread });
895
- }
896
- async updateThread({
897
- id,
898
- title,
899
- metadata
900
- }) {
901
- return this.memory.updateThread({ id, title, metadata });
902
- }
903
- async deleteThread({ threadId }) {
904
- await this.memory.deleteThread({ threadId });
905
- }
906
- async listMessages(args) {
907
- return this.memory.listMessages(args);
908
- }
909
- async listMessagesById({ messageIds }) {
910
- return this.memory.listMessagesById({ messageIds });
911
- }
912
- async saveMessages(args) {
913
- return this.memory.saveMessages(args);
914
- }
915
- async updateMessages({
916
- messages
917
- }) {
918
- return this.memory.updateMessages({ messages });
919
- }
920
- async deleteMessages(messageIds) {
921
- await this.memory.deleteMessages(messageIds);
922
- }
923
- async listThreadsByResourceId(args) {
924
- return this.memory.listThreadsByResourceId(args);
925
- }
926
- async getResourceById({ resourceId }) {
927
- return this.memory.getResourceById({ resourceId });
928
- }
929
- async saveResource({ resource }) {
930
- return this.memory.saveResource({ resource });
931
- }
932
- async updateResource({
933
- resourceId,
934
- workingMemory,
935
- metadata
936
- }) {
937
- return this.memory.updateResource({ resourceId, workingMemory, metadata });
938
- }
939
- async updateWorkflowResults(params) {
940
- return this.workflows.updateWorkflowResults(params);
941
- }
942
- async updateWorkflowState(params) {
943
- return this.workflows.updateWorkflowState(params);
944
- }
945
- async persistWorkflowSnapshot({
946
- workflowName,
947
- runId,
948
- resourceId,
949
- snapshot
950
- }) {
951
- await this.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
952
- }
953
- async loadWorkflowSnapshot({
954
- workflowName,
955
- runId
956
- }) {
957
- return this.workflows.loadWorkflowSnapshot({ workflowName, runId });
958
- }
959
- async listWorkflowRuns(args) {
960
- return this.workflows.listWorkflowRuns(args);
961
- }
962
- async getWorkflowRunById({
963
- runId,
964
- workflowName
965
- }) {
966
- return this.workflows.getWorkflowRunById({ runId, workflowName });
967
- }
968
- async deleteWorkflowRunById({ runId, workflowName }) {
969
- return this.workflows.deleteWorkflowRunById({ runId, workflowName });
970
- }
971
- async getScoreById({ id }) {
972
- return this.scores.getScoreById({ id });
973
- }
974
- async saveScore(score) {
975
- return this.scores.saveScore(score);
976
- }
977
- async listScoresByScorerId({
978
- scorerId,
979
- pagination,
980
- entityId,
981
- entityType,
982
- source
983
- }) {
984
- return this.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
985
- }
986
- async listScoresByRunId({
987
- runId,
988
- pagination
989
- }) {
990
- return this.scores.listScoresByRunId({ runId, pagination });
991
- }
992
- async listScoresByEntityId({
993
- entityId,
994
- entityType,
995
- pagination
996
- }) {
997
- return this.scores.listScoresByEntityId({ entityId, entityType, pagination });
998
- }
999
907
  };
1000
908
  var INDEX_METADATA_TABLE = "mastra_vector_indexes";
1001
909
  var ConvexVector = class extends vector.MastraVector {
@@ -1306,55 +1214,55 @@ Object.defineProperty(exports, "mastraStorage", {
1306
1214
  });
1307
1215
  Object.defineProperty(exports, "TABLE_MESSAGES", {
1308
1216
  enumerable: true,
1309
- get: function () { return chunkZBUP3DS6_cjs.TABLE_MESSAGES; }
1217
+ get: function () { return chunkFTVDAP6U_cjs.TABLE_MESSAGES; }
1310
1218
  });
1311
1219
  Object.defineProperty(exports, "TABLE_RESOURCES", {
1312
1220
  enumerable: true,
1313
- get: function () { return chunkZBUP3DS6_cjs.TABLE_RESOURCES; }
1221
+ get: function () { return chunkFTVDAP6U_cjs.TABLE_RESOURCES; }
1314
1222
  });
1315
1223
  Object.defineProperty(exports, "TABLE_SCORERS", {
1316
1224
  enumerable: true,
1317
- get: function () { return chunkZBUP3DS6_cjs.TABLE_SCORERS; }
1225
+ get: function () { return chunkFTVDAP6U_cjs.TABLE_SCORERS; }
1318
1226
  });
1319
1227
  Object.defineProperty(exports, "TABLE_THREADS", {
1320
1228
  enumerable: true,
1321
- get: function () { return chunkZBUP3DS6_cjs.TABLE_THREADS; }
1229
+ get: function () { return chunkFTVDAP6U_cjs.TABLE_THREADS; }
1322
1230
  });
1323
1231
  Object.defineProperty(exports, "TABLE_WORKFLOW_SNAPSHOT", {
1324
1232
  enumerable: true,
1325
- get: function () { return chunkZBUP3DS6_cjs.TABLE_WORKFLOW_SNAPSHOT; }
1233
+ get: function () { return chunkFTVDAP6U_cjs.TABLE_WORKFLOW_SNAPSHOT; }
1326
1234
  });
1327
1235
  Object.defineProperty(exports, "mastraDocumentsTable", {
1328
1236
  enumerable: true,
1329
- get: function () { return chunkZBUP3DS6_cjs.mastraDocumentsTable; }
1237
+ get: function () { return chunkFTVDAP6U_cjs.mastraDocumentsTable; }
1330
1238
  });
1331
1239
  Object.defineProperty(exports, "mastraMessagesTable", {
1332
1240
  enumerable: true,
1333
- get: function () { return chunkZBUP3DS6_cjs.mastraMessagesTable; }
1241
+ get: function () { return chunkFTVDAP6U_cjs.mastraMessagesTable; }
1334
1242
  });
1335
1243
  Object.defineProperty(exports, "mastraResourcesTable", {
1336
1244
  enumerable: true,
1337
- get: function () { return chunkZBUP3DS6_cjs.mastraResourcesTable; }
1245
+ get: function () { return chunkFTVDAP6U_cjs.mastraResourcesTable; }
1338
1246
  });
1339
1247
  Object.defineProperty(exports, "mastraScoresTable", {
1340
1248
  enumerable: true,
1341
- get: function () { return chunkZBUP3DS6_cjs.mastraScoresTable; }
1249
+ get: function () { return chunkFTVDAP6U_cjs.mastraScoresTable; }
1342
1250
  });
1343
1251
  Object.defineProperty(exports, "mastraThreadsTable", {
1344
1252
  enumerable: true,
1345
- get: function () { return chunkZBUP3DS6_cjs.mastraThreadsTable; }
1253
+ get: function () { return chunkFTVDAP6U_cjs.mastraThreadsTable; }
1346
1254
  });
1347
1255
  Object.defineProperty(exports, "mastraVectorIndexesTable", {
1348
1256
  enumerable: true,
1349
- get: function () { return chunkZBUP3DS6_cjs.mastraVectorIndexesTable; }
1257
+ get: function () { return chunkFTVDAP6U_cjs.mastraVectorIndexesTable; }
1350
1258
  });
1351
1259
  Object.defineProperty(exports, "mastraVectorsTable", {
1352
1260
  enumerable: true,
1353
- get: function () { return chunkZBUP3DS6_cjs.mastraVectorsTable; }
1261
+ get: function () { return chunkFTVDAP6U_cjs.mastraVectorsTable; }
1354
1262
  });
1355
1263
  Object.defineProperty(exports, "mastraWorkflowSnapshotsTable", {
1356
1264
  enumerable: true,
1357
- get: function () { return chunkZBUP3DS6_cjs.mastraWorkflowSnapshotsTable; }
1265
+ get: function () { return chunkFTVDAP6U_cjs.mastraWorkflowSnapshotsTable; }
1358
1266
  });
1359
1267
  exports.ConvexStore = ConvexStore;
1360
1268
  exports.ConvexVector = ConvexVector;