@mastra/server 0.0.0-a2a-20250421213654

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 (97) hide show
  1. package/LICENSE.md +46 -0
  2. package/README.md +159 -0
  3. package/dist/_tsup-dts-rollup.d.cts +897 -0
  4. package/dist/_tsup-dts-rollup.d.ts +897 -0
  5. package/dist/chunk-3KWAWPRU.cjs +127 -0
  6. package/dist/chunk-4VNS5WPM.js +37 -0
  7. package/dist/chunk-57CJTIPW.cjs +18 -0
  8. package/dist/chunk-5SWCVTNL.cjs +5579 -0
  9. package/dist/chunk-64U3UDTH.cjs +13 -0
  10. package/dist/chunk-6QEBCWQG.js +136 -0
  11. package/dist/chunk-75KYFUMD.cjs +165 -0
  12. package/dist/chunk-B2TWGIVC.cjs +101 -0
  13. package/dist/chunk-CVPOREIE.cjs +42 -0
  14. package/dist/chunk-CZOSYERC.js +312 -0
  15. package/dist/chunk-FFRES7WX.js +157 -0
  16. package/dist/chunk-H5PTF3Y4.js +16 -0
  17. package/dist/chunk-IDPBXKRV.js +121 -0
  18. package/dist/chunk-J2MCTUD4.js +121 -0
  19. package/dist/chunk-JQCFFVSK.cjs +127 -0
  20. package/dist/chunk-LGJ46RCS.js +96 -0
  21. package/dist/chunk-LTP7PHVE.cjs +321 -0
  22. package/dist/chunk-M5ABIP7D.js +11 -0
  23. package/dist/chunk-NJF275KR.js +49 -0
  24. package/dist/chunk-NYN7KFXL.js +34 -0
  25. package/dist/chunk-O7X557PN.cjs +140 -0
  26. package/dist/chunk-OCWPVYNI.cjs +36 -0
  27. package/dist/chunk-OMN3UI6X.js +5576 -0
  28. package/dist/chunk-P7UZNROR.js +306 -0
  29. package/dist/chunk-PJHJORJL.js +204 -0
  30. package/dist/chunk-RXH2S65Z.cjs +54 -0
  31. package/dist/chunk-UVVUDJBW.cjs +214 -0
  32. package/dist/chunk-Y7WN2UYV.cjs +318 -0
  33. package/dist/chunk-YB2FGKQ5.js +121 -0
  34. package/dist/chunk-ZCRMOXNW.cjs +129 -0
  35. package/dist/index.cjs +2 -0
  36. package/dist/index.d.cts +1 -0
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +1 -0
  39. package/dist/magic-string.es-5UDOWOAZ.js +1294 -0
  40. package/dist/magic-string.es-IL2775P6.cjs +1300 -0
  41. package/dist/server/handlers/a2a.cjs +34 -0
  42. package/dist/server/handlers/a2a.d.cts +7 -0
  43. package/dist/server/handlers/a2a.d.ts +7 -0
  44. package/dist/server/handlers/a2a.js +1 -0
  45. package/dist/server/handlers/agents.cjs +30 -0
  46. package/dist/server/handlers/agents.d.cts +6 -0
  47. package/dist/server/handlers/agents.d.ts +6 -0
  48. package/dist/server/handlers/agents.js +1 -0
  49. package/dist/server/handlers/error.cjs +10 -0
  50. package/dist/server/handlers/error.d.cts +1 -0
  51. package/dist/server/handlers/error.d.ts +1 -0
  52. package/dist/server/handlers/error.js +1 -0
  53. package/dist/server/handlers/logs.cjs +18 -0
  54. package/dist/server/handlers/logs.d.cts +3 -0
  55. package/dist/server/handlers/logs.d.ts +3 -0
  56. package/dist/server/handlers/logs.js +1 -0
  57. package/dist/server/handlers/memory.cjs +38 -0
  58. package/dist/server/handlers/memory.d.cts +8 -0
  59. package/dist/server/handlers/memory.d.ts +8 -0
  60. package/dist/server/handlers/memory.js +1 -0
  61. package/dist/server/handlers/network.cjs +22 -0
  62. package/dist/server/handlers/network.d.cts +4 -0
  63. package/dist/server/handlers/network.d.ts +4 -0
  64. package/dist/server/handlers/network.js +1 -0
  65. package/dist/server/handlers/telemetry.cjs +14 -0
  66. package/dist/server/handlers/telemetry.d.cts +2 -0
  67. package/dist/server/handlers/telemetry.d.ts +2 -0
  68. package/dist/server/handlers/telemetry.js +1 -0
  69. package/dist/server/handlers/test-utils.cjs +16209 -0
  70. package/dist/server/handlers/test-utils.d.cts +1 -0
  71. package/dist/server/handlers/test-utils.d.ts +1 -0
  72. package/dist/server/handlers/test-utils.js +16207 -0
  73. package/dist/server/handlers/tools.cjs +22 -0
  74. package/dist/server/handlers/tools.d.cts +4 -0
  75. package/dist/server/handlers/tools.d.ts +4 -0
  76. package/dist/server/handlers/tools.js +1 -0
  77. package/dist/server/handlers/utils.cjs +10 -0
  78. package/dist/server/handlers/utils.d.cts +1 -0
  79. package/dist/server/handlers/utils.d.ts +1 -0
  80. package/dist/server/handlers/utils.js +1 -0
  81. package/dist/server/handlers/vector.cjs +30 -0
  82. package/dist/server/handlers/vector.d.cts +6 -0
  83. package/dist/server/handlers/vector.d.ts +6 -0
  84. package/dist/server/handlers/vector.js +1 -0
  85. package/dist/server/handlers/voice.cjs +18 -0
  86. package/dist/server/handlers/voice.d.cts +3 -0
  87. package/dist/server/handlers/voice.d.ts +3 -0
  88. package/dist/server/handlers/voice.js +1 -0
  89. package/dist/server/handlers/workflows.cjs +46 -0
  90. package/dist/server/handlers/workflows.d.cts +10 -0
  91. package/dist/server/handlers/workflows.d.ts +10 -0
  92. package/dist/server/handlers/workflows.js +1 -0
  93. package/dist/server/handlers.cjs +55 -0
  94. package/dist/server/handlers.d.cts +10 -0
  95. package/dist/server/handlers.d.ts +10 -0
  96. package/dist/server/handlers.js +10 -0
  97. package/package.json +71 -0
@@ -0,0 +1,312 @@
1
+ import { __export } from './chunk-4VNS5WPM.js';
2
+
3
+ // src/server/handlers/a2a.ts
4
+ var a2a_exports = {};
5
+ __export(a2a_exports, {
6
+ generateAgentCard: () => generateAgentCard,
7
+ handleA2ARequest: () => handleA2ARequest,
8
+ handleAgentCardRequest: () => handleAgentCardRequest,
9
+ handleCancelTask: () => handleCancelTask,
10
+ handleGetTask: () => handleGetTask,
11
+ handlePushNotification: () => handlePushNotification,
12
+ handleSendTask: () => handleSendTask
13
+ });
14
+ var tasks = /* @__PURE__ */ new Map();
15
+ function convertToA2AMessage({ message, role }) {
16
+ if (typeof message === "string") {
17
+ return {
18
+ role,
19
+ parts: [
20
+ {
21
+ type: "text",
22
+ text: message
23
+ }
24
+ ]
25
+ };
26
+ }
27
+ if (message && message.text) {
28
+ return {
29
+ role,
30
+ parts: [
31
+ {
32
+ type: "text",
33
+ text: message.text
34
+ }
35
+ ]
36
+ };
37
+ }
38
+ let parts = [];
39
+ if (message && message.content) {
40
+ if (typeof message.content === "string") {
41
+ parts.push({
42
+ type: "text",
43
+ text: message.content
44
+ });
45
+ } else if (Array.isArray(message.content)) {
46
+ parts = message.content.map((item) => {
47
+ if (typeof item === "string") {
48
+ return {
49
+ type: "text",
50
+ text: item
51
+ };
52
+ } else if (item && item.type === "text") {
53
+ return {
54
+ type: "text",
55
+ text: item.text || ""
56
+ };
57
+ } else if (item && item.type === "file") {
58
+ return {
59
+ type: "file",
60
+ file: {
61
+ name: item.name || null,
62
+ mimeType: item.mimeType || null,
63
+ uri: item.uri || null
64
+ }
65
+ };
66
+ } else {
67
+ return {
68
+ type: "data",
69
+ data: item || {}
70
+ };
71
+ }
72
+ });
73
+ }
74
+ }
75
+ if (parts.length === 0 && typeof message === "object" && message !== null) {
76
+ try {
77
+ const textRepresentation = JSON.stringify(message, null, 2);
78
+ parts.push({
79
+ type: "text",
80
+ text: textRepresentation
81
+ });
82
+ } catch (_e) {
83
+ parts.push({
84
+ type: "text",
85
+ text: "Unable to convert agent response to text"
86
+ });
87
+ }
88
+ }
89
+ return {
90
+ role,
91
+ parts
92
+ };
93
+ }
94
+ function convertFromA2AMessage({ message }) {
95
+ if (message.parts && message.parts.length === 1 && message.parts[0]?.type === "text") {
96
+ return message.parts[0]?.text || "";
97
+ }
98
+ const content = (message.parts || []).map((part) => {
99
+ if (part.type === "text") {
100
+ return part.text || "";
101
+ } else if (part.type === "file" && part.file) {
102
+ return {
103
+ type: "file",
104
+ name: part.file.name || "",
105
+ mimeType: part.file.mimeType || "",
106
+ uri: part.file.uri || ""
107
+ };
108
+ } else if (part.type === "data") {
109
+ return part.data || {};
110
+ }
111
+ return null;
112
+ }).filter(Boolean);
113
+ return {
114
+ role: message.role || "user",
115
+ content: content.length === 1 ? content[0] : content
116
+ };
117
+ }
118
+ function createErrorResponse({
119
+ id,
120
+ code,
121
+ message,
122
+ data
123
+ }) {
124
+ return {
125
+ jsonrpc: "2.0",
126
+ id,
127
+ error: {
128
+ code,
129
+ message,
130
+ data
131
+ }
132
+ };
133
+ }
134
+ function createSuccessResponse({ id, result }) {
135
+ return {
136
+ jsonrpc: "2.0",
137
+ id,
138
+ result
139
+ };
140
+ }
141
+ async function handleSendTask({
142
+ request,
143
+ agent
144
+ }) {
145
+ try {
146
+ const { id, message, sessionId } = request.params;
147
+ const agentMessage = convertFromA2AMessage({ message });
148
+ const response = await agent.generate(agentMessage);
149
+ const a2aResponse = convertToA2AMessage({ message: response, role: "agent" });
150
+ const now = (/* @__PURE__ */ new Date()).toISOString();
151
+ const task = {
152
+ id,
153
+ sessionId: sessionId || null,
154
+ status: {
155
+ state: "completed" /* COMPLETED */,
156
+ message: a2aResponse,
157
+ timestamp: now
158
+ },
159
+ history: [message, a2aResponse]
160
+ };
161
+ tasks.set(id, task);
162
+ return createSuccessResponse({ id: request.id || null, result: task });
163
+ } catch (error) {
164
+ console.error("Error handling send task:", error);
165
+ return createErrorResponse({
166
+ id: request.id || null,
167
+ code: -32603 /* INTERNAL_ERROR */,
168
+ message: "Internal error processing task",
169
+ data: { error: String(error) }
170
+ });
171
+ }
172
+ }
173
+ async function handleGetTask({ request }) {
174
+ try {
175
+ const { id, historyLength } = request.params;
176
+ const task = tasks.get(id);
177
+ if (!task) {
178
+ return createErrorResponse({
179
+ id: request.id || null,
180
+ code: -32001 /* TASK_NOT_FOUND */,
181
+ message: "Task not found"
182
+ });
183
+ }
184
+ if (historyLength !== void 0 && historyLength !== null && task.history) {
185
+ task.history = task.history.slice(-historyLength);
186
+ }
187
+ return createSuccessResponse({ id: request.id || null, result: task });
188
+ } catch (error) {
189
+ console.error("Error handling get task:", error);
190
+ return createErrorResponse({
191
+ id: request.id || null,
192
+ code: -32603 /* INTERNAL_ERROR */,
193
+ message: "Internal error retrieving task",
194
+ data: { error: String(error) }
195
+ });
196
+ }
197
+ }
198
+ async function handleCancelTask({ request }) {
199
+ try {
200
+ const { id } = request.params;
201
+ const task = tasks.get(id);
202
+ if (!task) {
203
+ return createErrorResponse({
204
+ id: request.id || null,
205
+ code: -32001 /* TASK_NOT_FOUND */,
206
+ message: "Task not found"
207
+ });
208
+ }
209
+ if (task.status.state === "completed" /* COMPLETED */ || task.status.state === "canceled" /* CANCELED */ || task.status.state === "failed" /* FAILED */) {
210
+ return createErrorResponse({
211
+ id: request.id || null,
212
+ code: -32002 /* TASK_NOT_CANCELABLE */,
213
+ message: "Task cannot be canceled"
214
+ });
215
+ }
216
+ task.status = {
217
+ state: "canceled" /* CANCELED */,
218
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
219
+ };
220
+ tasks.set(id, task);
221
+ return createSuccessResponse({ id: request.id || null, result: task });
222
+ } catch (error) {
223
+ console.error("Error handling cancel task:", error);
224
+ return createErrorResponse({
225
+ id: request.id || null,
226
+ code: -32603 /* INTERNAL_ERROR */,
227
+ message: "Internal error canceling task",
228
+ data: { error: String(error) }
229
+ });
230
+ }
231
+ }
232
+ function handlePushNotification() {
233
+ return createErrorResponse({
234
+ id: null,
235
+ code: -32003 /* PUSH_NOTIFICATION_NOT_SUPPORTED */,
236
+ message: "Push Notification is not supported"
237
+ });
238
+ }
239
+ async function handleA2ARequest({
240
+ request,
241
+ agent
242
+ }) {
243
+ try {
244
+ const requestId = "id" in request ? request.id : null;
245
+ switch (request.method) {
246
+ case "tasks/send":
247
+ return await handleSendTask({ request, agent });
248
+ case "tasks/get":
249
+ return await handleGetTask({ request });
250
+ case "tasks/cancel":
251
+ return await handleCancelTask({ request });
252
+ case "tasks/pushNotification/set":
253
+ case "tasks/pushNotification/get":
254
+ case "tasks/resubscribe":
255
+ return handlePushNotification();
256
+ default:
257
+ return createErrorResponse({
258
+ id: requestId,
259
+ code: -32601 /* METHOD_NOT_FOUND */,
260
+ message: "Method not found"
261
+ });
262
+ }
263
+ } catch (error) {
264
+ console.error("Error handling A2A request:", error);
265
+ const errorRequestId = "id" in request && request.id !== void 0 ? request.id : null;
266
+ return createErrorResponse({
267
+ id: errorRequestId,
268
+ code: -32603 /* INTERNAL_ERROR */,
269
+ message: "Internal error",
270
+ data: { error: String(error) }
271
+ });
272
+ }
273
+ }
274
+ function generateAgentCard({ agent, baseUrl }) {
275
+ const skills = [];
276
+ if (agent.tools) {
277
+ Object.entries(agent.tools).forEach(([id, tool]) => {
278
+ const toolName = typeof tool === "object" && tool !== null ? tool.id || id : id;
279
+ const toolDescription = typeof tool === "object" && tool !== null ? tool.description || null : null;
280
+ skills.push({
281
+ id,
282
+ name: toolName,
283
+ description: toolDescription
284
+ });
285
+ });
286
+ }
287
+ if (skills.length === 0) {
288
+ skills.push({
289
+ id: "conversation",
290
+ name: "Conversation",
291
+ description: "General conversation capabilities"
292
+ });
293
+ }
294
+ const capabilities = {
295
+ streaming: false,
296
+ pushNotifications: false,
297
+ stateTransitionHistory: false
298
+ };
299
+ return {
300
+ name: agent.name || "Mastra Agent",
301
+ description: typeof agent.instructions === "string" ? agent.instructions : null,
302
+ url: `${baseUrl}/a2a`,
303
+ version: "1.0.0",
304
+ capabilities,
305
+ skills
306
+ };
307
+ }
308
+ function handleAgentCardRequest({ agent, baseUrl }) {
309
+ return generateAgentCard({ agent, baseUrl });
310
+ }
311
+
312
+ export { a2a_exports, generateAgentCard, handleA2ARequest, handleAgentCardRequest, handleCancelTask, handleGetTask, handlePushNotification, handleSendTask };
@@ -0,0 +1,157 @@
1
+ import { stringify, esm_default } from './chunk-OMN3UI6X.js';
2
+ import { validateBody } from './chunk-H5PTF3Y4.js';
3
+ import { handleError } from './chunk-M5ABIP7D.js';
4
+ import { HTTPException } from './chunk-NYN7KFXL.js';
5
+ import { __export } from './chunk-4VNS5WPM.js';
6
+
7
+ // src/server/handlers/agents.ts
8
+ var agents_exports = {};
9
+ __export(agents_exports, {
10
+ generateHandler: () => generateHandler,
11
+ getAgentByIdHandler: () => getAgentByIdHandler,
12
+ getAgentsHandler: () => getAgentsHandler,
13
+ getEvalsByAgentIdHandler: () => getEvalsByAgentIdHandler,
14
+ getLiveEvalsByAgentIdHandler: () => getLiveEvalsByAgentIdHandler,
15
+ streamGenerateHandler: () => streamGenerateHandler
16
+ });
17
+ async function getAgentsHandler({ mastra }) {
18
+ try {
19
+ const agents = mastra.getAgents();
20
+ const serializedAgents = Object.entries(agents).reduce((acc, [_id, _agent]) => {
21
+ const agent = _agent;
22
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc2, [key, tool]) => {
23
+ const _tool = tool;
24
+ acc2[key] = {
25
+ ..._tool,
26
+ inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
27
+ outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
28
+ };
29
+ return acc2;
30
+ }, {});
31
+ acc[_id] = {
32
+ name: agent.name,
33
+ instructions: agent.instructions,
34
+ tools: serializedAgentTools,
35
+ provider: agent.llm?.getProvider(),
36
+ modelId: agent.llm?.getModelId()
37
+ };
38
+ return acc;
39
+ }, {});
40
+ return serializedAgents;
41
+ } catch (error) {
42
+ return handleError(error, "Error getting agents");
43
+ }
44
+ }
45
+ async function getAgentByIdHandler({ mastra, agentId }) {
46
+ try {
47
+ const agent = mastra.getAgent(agentId);
48
+ if (!agent) {
49
+ throw new HTTPException(404, { message: "Agent not found" });
50
+ }
51
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc, [key, tool]) => {
52
+ const _tool = tool;
53
+ acc[key] = {
54
+ ..._tool,
55
+ inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
56
+ outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
57
+ };
58
+ return acc;
59
+ }, {});
60
+ return {
61
+ name: agent.name,
62
+ instructions: agent.instructions,
63
+ tools: serializedAgentTools,
64
+ provider: agent.llm?.getProvider(),
65
+ modelId: agent.llm?.getModelId()
66
+ };
67
+ } catch (error) {
68
+ return handleError(error, "Error getting agent");
69
+ }
70
+ }
71
+ async function getEvalsByAgentIdHandler({ mastra, agentId }) {
72
+ try {
73
+ const agent = mastra.getAgent(agentId);
74
+ const evals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "test") || [];
75
+ return {
76
+ id: agentId,
77
+ name: agent.name,
78
+ instructions: agent.instructions,
79
+ evals
80
+ };
81
+ } catch (error) {
82
+ return handleError(error, "Error getting test evals");
83
+ }
84
+ }
85
+ async function getLiveEvalsByAgentIdHandler({ mastra, agentId }) {
86
+ try {
87
+ const agent = mastra.getAgent(agentId);
88
+ const evals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "live") || [];
89
+ return {
90
+ id: agentId,
91
+ name: agent.name,
92
+ instructions: agent.instructions,
93
+ evals
94
+ };
95
+ } catch (error) {
96
+ return handleError(error, "Error getting live evals");
97
+ }
98
+ }
99
+ async function generateHandler({
100
+ mastra,
101
+ container,
102
+ agentId,
103
+ body
104
+ }) {
105
+ try {
106
+ const agent = mastra.getAgent(agentId);
107
+ if (!agent) {
108
+ throw new HTTPException(404, { message: "Agent not found" });
109
+ }
110
+ const { messages, resourceId, resourceid, ...rest } = body;
111
+ const finalResourceId = resourceId ?? resourceid;
112
+ validateBody({ messages });
113
+ const result = await agent.generate(messages, {
114
+ ...rest,
115
+ // @ts-expect-error TODO fix types
116
+ resourceId: finalResourceId,
117
+ container
118
+ });
119
+ return result;
120
+ } catch (error) {
121
+ return handleError(error, "Error generating from agent");
122
+ }
123
+ }
124
+ async function streamGenerateHandler({
125
+ mastra,
126
+ container,
127
+ agentId,
128
+ body
129
+ }) {
130
+ try {
131
+ const agent = mastra.getAgent(agentId);
132
+ if (!agent) {
133
+ throw new HTTPException(404, { message: "Agent not found" });
134
+ }
135
+ const { messages, resourceId, resourceid, ...rest } = body;
136
+ const finalResourceId = resourceId ?? resourceid;
137
+ validateBody({ messages });
138
+ const streamResult = await agent.stream(messages, {
139
+ ...rest,
140
+ // @ts-expect-error TODO fix types
141
+ resourceId: finalResourceId,
142
+ container
143
+ });
144
+ const streamResponse = rest.output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
145
+ sendUsage: true,
146
+ sendReasoning: true,
147
+ getErrorMessage: (error) => {
148
+ return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
149
+ }
150
+ });
151
+ return streamResponse;
152
+ } catch (error) {
153
+ throw new HTTPException(error?.status ?? 500, { message: error?.message ?? "Error streaming from agent" });
154
+ }
155
+ }
156
+
157
+ export { agents_exports, generateHandler, getAgentByIdHandler, getAgentsHandler, getEvalsByAgentIdHandler, getLiveEvalsByAgentIdHandler, streamGenerateHandler };
@@ -0,0 +1,16 @@
1
+ import { HTTPException } from './chunk-NYN7KFXL.js';
2
+
3
+ // src/server/handlers/utils.ts
4
+ function validateBody(body) {
5
+ const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
6
+ if (!value) {
7
+ acc[key] = `Argument "${key}" is required`;
8
+ }
9
+ return acc;
10
+ }, {});
11
+ if (Object.keys(errorResponse).length > 0) {
12
+ throw new HTTPException(400, { message: Object.values(errorResponse)[0] });
13
+ }
14
+ }
15
+
16
+ export { validateBody };
@@ -0,0 +1,121 @@
1
+ import { handleError } from './chunk-M5ABIP7D.js';
2
+ import { HTTPException } from './chunk-NYN7KFXL.js';
3
+ import { __export } from './chunk-4VNS5WPM.js';
4
+
5
+ // src/server/handlers/vector.ts
6
+ var vector_exports = {};
7
+ __export(vector_exports, {
8
+ createIndex: () => createIndex,
9
+ deleteIndex: () => deleteIndex,
10
+ describeIndex: () => describeIndex,
11
+ listIndexes: () => listIndexes,
12
+ queryVectors: () => queryVectors,
13
+ upsertVectors: () => upsertVectors
14
+ });
15
+ function getVector(mastra, vectorName) {
16
+ if (!vectorName) {
17
+ throw new HTTPException(400, { message: "Vector name is required" });
18
+ }
19
+ const vector = mastra.getVector(vectorName);
20
+ if (!vector) {
21
+ throw new HTTPException(404, { message: `Vector store ${vectorName} not found` });
22
+ }
23
+ return vector;
24
+ }
25
+ async function upsertVectors({ mastra, vectorName, index }) {
26
+ try {
27
+ if (!index?.indexName || !index?.vectors || !Array.isArray(index.vectors)) {
28
+ throw new HTTPException(400, { message: "Invalid request index. indexName and vectors array are required." });
29
+ }
30
+ const vector = getVector(mastra, vectorName);
31
+ const result = await vector.upsert(index);
32
+ return { ids: result };
33
+ } catch (error) {
34
+ return handleError(error, "Error upserting vectors");
35
+ }
36
+ }
37
+ async function createIndex({
38
+ mastra,
39
+ vectorName,
40
+ index
41
+ }) {
42
+ try {
43
+ const { indexName, dimension, metric } = index;
44
+ if (!indexName || typeof dimension !== "number" || dimension <= 0) {
45
+ throw new HTTPException(400, {
46
+ message: "Invalid request index, indexName and positive dimension number are required."
47
+ });
48
+ }
49
+ if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
50
+ throw new HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
51
+ }
52
+ const vector = getVector(mastra, vectorName);
53
+ await vector.createIndex({ indexName, dimension, metric });
54
+ return { success: true };
55
+ } catch (error) {
56
+ return handleError(error, "Error creating index");
57
+ }
58
+ }
59
+ async function queryVectors({
60
+ mastra,
61
+ vectorName,
62
+ query
63
+ }) {
64
+ try {
65
+ if (!query?.indexName || !query?.queryVector || !Array.isArray(query.queryVector)) {
66
+ throw new HTTPException(400, { message: "Invalid request query. indexName and queryVector array are required." });
67
+ }
68
+ const vector = getVector(mastra, vectorName);
69
+ const results = await vector.query(query);
70
+ return results;
71
+ } catch (error) {
72
+ return handleError(error, "Error querying vectors");
73
+ }
74
+ }
75
+ async function listIndexes({ mastra, vectorName }) {
76
+ try {
77
+ const vector = getVector(mastra, vectorName);
78
+ const indexes = await vector.listIndexes();
79
+ return indexes.filter(Boolean);
80
+ } catch (error) {
81
+ return handleError(error, "Error listing indexes");
82
+ }
83
+ }
84
+ async function describeIndex({
85
+ mastra,
86
+ vectorName,
87
+ indexName
88
+ }) {
89
+ try {
90
+ if (!indexName) {
91
+ throw new HTTPException(400, { message: "Index name is required" });
92
+ }
93
+ const vector = getVector(mastra, vectorName);
94
+ const stats = await vector.describeIndex(indexName);
95
+ return {
96
+ dimension: stats.dimension,
97
+ count: stats.count,
98
+ metric: stats.metric?.toLowerCase()
99
+ };
100
+ } catch (error) {
101
+ return handleError(error, "Error describing index");
102
+ }
103
+ }
104
+ async function deleteIndex({
105
+ mastra,
106
+ vectorName,
107
+ indexName
108
+ }) {
109
+ try {
110
+ if (!indexName) {
111
+ throw new HTTPException(400, { message: "Index name is required" });
112
+ }
113
+ const vector = getVector(mastra, vectorName);
114
+ await vector.deleteIndex(indexName);
115
+ return { success: true };
116
+ } catch (error) {
117
+ return handleError(error, "Error deleting index");
118
+ }
119
+ }
120
+
121
+ export { createIndex, deleteIndex, describeIndex, listIndexes, queryVectors, upsertVectors, vector_exports };