@mastra/server 0.0.0-fix-memory-xxhash-20250409202110 → 0.0.0-generate-message-id-20250512171942

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 (75) hide show
  1. package/{LICENSE → LICENSE.md} +3 -1
  2. package/README.md +48 -135
  3. package/dist/_tsup-dts-rollup.d.cts +282 -34
  4. package/dist/_tsup-dts-rollup.d.ts +282 -34
  5. package/dist/{chunk-2FJURXCL.cjs → chunk-24EGIVT7.cjs} +34 -33
  6. package/dist/chunk-3HQNCTZ2.cjs +199 -0
  7. package/dist/{chunk-M56ECCHK.cjs → chunk-4YZ3U35L.cjs} +18 -17
  8. package/dist/{chunk-QN4KF3BH.cjs → chunk-57CJTIPW.cjs} +2 -2
  9. package/dist/chunk-5SN4U5AC.cjs +508 -0
  10. package/dist/{chunk-ZLBRQFDD.cjs → chunk-64U3UDTH.cjs} +2 -2
  11. package/dist/chunk-75ZPJI57.cjs +9 -0
  12. package/dist/{chunk-2YONKUWB.js → chunk-C7564HUT.js} +58 -33
  13. package/dist/{chunk-ILW7XYNJ.js → chunk-EJO45KYT.js} +51 -27
  14. package/dist/{chunk-L7XE5QTW.js → chunk-H5PTF3Y4.js} +1 -1
  15. package/dist/{chunk-3RVHWGWO.js → chunk-HFWCEP5S.js} +6 -12
  16. package/dist/{chunk-2JQC6JWP.js → chunk-HWZVAG3H.js} +7 -4
  17. package/dist/{chunk-X37I6GZT.cjs → chunk-I2B73Y4I.cjs} +92 -68
  18. package/dist/{chunk-4JINXASC.js → chunk-IU5VO2I2.js} +3 -2
  19. package/dist/chunk-LIVAK2DM.js +2001 -0
  20. package/dist/{chunk-3AHQ5RGN.js → chunk-M5ABIP7D.js} +1 -1
  21. package/dist/{chunk-CWSDZEZG.cjs → chunk-MHKNLNAN.cjs} +15 -12
  22. package/dist/chunk-MIQYDLLM.js +329 -0
  23. package/dist/chunk-MLKGABMK.js +7 -0
  24. package/dist/{chunk-TRDNDNGQ.js → chunk-NYN7KFXL.js} +1 -7
  25. package/dist/{chunk-FV45V6WC.cjs → chunk-OCWPVYNI.cjs} +0 -7
  26. package/dist/{chunk-VB7KH62D.cjs → chunk-OGCNNUHF.cjs} +13 -10
  27. package/dist/{chunk-DVPP5S6I.js → chunk-OR3CIE2H.js} +9 -6
  28. package/dist/chunk-P6SCPDYW.js +500 -0
  29. package/dist/{chunk-BMA2ORRT.js → chunk-Q6KMBIAN.js} +76 -37
  30. package/dist/{chunk-YNSGUC2O.js → chunk-TJKLBTFB.js} +23 -7
  31. package/dist/chunk-UCTEMO2Q.cjs +341 -0
  32. package/dist/chunk-VPNDC2DI.cjs +148 -0
  33. package/dist/{chunk-RBQASTUP.js → chunk-X3ZDCS52.js} +4 -3
  34. package/dist/{chunk-A7DF4ETD.cjs → chunk-YBVOQN4M.cjs} +22 -28
  35. package/dist/chunk-YWLUOY3D.cjs +2004 -0
  36. package/dist/{chunk-4C3EPMMF.cjs → chunk-ZE5AAC4I.cjs} +40 -24
  37. package/dist/server/handlers/a2a.cjs +30 -0
  38. package/dist/server/handlers/a2a.d.cts +6 -0
  39. package/dist/server/handlers/a2a.d.ts +6 -0
  40. package/dist/server/handlers/a2a.js +1 -0
  41. package/dist/server/handlers/agents.cjs +7 -7
  42. package/dist/server/handlers/agents.js +1 -1
  43. package/dist/server/handlers/error.cjs +2 -2
  44. package/dist/server/handlers/error.js +1 -1
  45. package/dist/server/handlers/logs.cjs +4 -4
  46. package/dist/server/handlers/logs.js +1 -1
  47. package/dist/server/handlers/memory.cjs +9 -9
  48. package/dist/server/handlers/memory.js +1 -1
  49. package/dist/server/handlers/network.cjs +5 -5
  50. package/dist/server/handlers/network.js +1 -1
  51. package/dist/server/handlers/telemetry.cjs +3 -3
  52. package/dist/server/handlers/telemetry.js +1 -1
  53. package/dist/server/handlers/tools.cjs +5 -5
  54. package/dist/server/handlers/tools.js +1 -1
  55. package/dist/server/handlers/utils.cjs +2 -2
  56. package/dist/server/handlers/utils.js +1 -1
  57. package/dist/server/handlers/vNextWorkflows.cjs +46 -0
  58. package/dist/server/handlers/vNextWorkflows.d.cts +10 -0
  59. package/dist/server/handlers/vNextWorkflows.d.ts +10 -0
  60. package/dist/server/handlers/vNextWorkflows.js +1 -0
  61. package/dist/server/handlers/vector.cjs +7 -7
  62. package/dist/server/handlers/vector.js +1 -1
  63. package/dist/server/handlers/voice.cjs +4 -4
  64. package/dist/server/handlers/voice.js +1 -1
  65. package/dist/server/handlers/workflows.cjs +11 -11
  66. package/dist/server/handlers/workflows.js +1 -1
  67. package/dist/server/handlers.cjs +31 -21
  68. package/dist/server/handlers.d.cts +2 -0
  69. package/dist/server/handlers.d.ts +2 -0
  70. package/dist/server/handlers.js +11 -9
  71. package/package.json +9 -7
  72. package/dist/chunk-5JOF627H.cjs +0 -123
  73. package/dist/chunk-GV52BII2.cjs +0 -160
  74. package/dist/chunk-QH6XWSXP.cjs +0 -5579
  75. package/dist/chunk-VK6FX47H.js +0 -5576
@@ -0,0 +1,500 @@
1
+ import { __export } from './chunk-MLKGABMK.js';
2
+ import { A2AError } from '@mastra/core/a2a';
3
+ import { z } from 'zod';
4
+
5
+ // src/server/handlers/a2a.ts
6
+ var a2a_exports = {};
7
+ __export(a2a_exports, {
8
+ getAgentCardByIdHandler: () => getAgentCardByIdHandler,
9
+ getAgentExecutionHandler: () => getAgentExecutionHandler,
10
+ handleTaskCancel: () => handleTaskCancel,
11
+ handleTaskGet: () => handleTaskGet,
12
+ handleTaskSend: () => handleTaskSend,
13
+ handleTaskSendSubscribe: () => handleTaskSendSubscribe
14
+ });
15
+ function normalizeError(error, reqId, taskId, logger) {
16
+ let a2aError;
17
+ if (error instanceof A2AError) {
18
+ a2aError = error;
19
+ } else if (error instanceof Error) {
20
+ a2aError = A2AError.internalError(error.message, { stack: error.stack });
21
+ } else {
22
+ a2aError = A2AError.internalError("An unknown error occurred.", error);
23
+ }
24
+ if (taskId && !a2aError.taskId) {
25
+ a2aError.taskId = taskId;
26
+ }
27
+ logger?.error(`Error processing request (Task: ${a2aError.taskId ?? "N/A"}, ReqID: ${reqId ?? "N/A"}):`, a2aError);
28
+ return createErrorResponse(reqId, a2aError.toJSONRPCError());
29
+ }
30
+ function createErrorResponse(id, error) {
31
+ return {
32
+ jsonrpc: "2.0",
33
+ id,
34
+ // Can be null if request ID was invalid/missing
35
+ error
36
+ };
37
+ }
38
+ function createSuccessResponse(id, result) {
39
+ if (!id) {
40
+ throw A2AError.internalError("Cannot create success response for null ID.");
41
+ }
42
+ return {
43
+ jsonrpc: "2.0",
44
+ id,
45
+ result
46
+ };
47
+ }
48
+ function convertToCoreMessage(message) {
49
+ return {
50
+ role: message.role === "user" ? "user" : "assistant",
51
+ content: message.parts.map((msg) => convertToCoreMessagePart(msg))
52
+ };
53
+ }
54
+ function convertToCoreMessagePart(part) {
55
+ switch (part.type) {
56
+ case "text":
57
+ return {
58
+ type: "text",
59
+ text: part.text
60
+ };
61
+ case "file":
62
+ return {
63
+ type: "file",
64
+ data: new URL(part.file.uri),
65
+ mimeType: part.file.mimeType
66
+ };
67
+ case "data":
68
+ throw new Error("Data parts are not supported in core messages");
69
+ }
70
+ }
71
+
72
+ // src/server/a2a/store.ts
73
+ var InMemoryTaskStore = class {
74
+ store = /* @__PURE__ */ new Map();
75
+ activeCancellations = /* @__PURE__ */ new Set();
76
+ async load({ agentId, taskId }) {
77
+ const entry = this.store.get(`${agentId}-${taskId}`);
78
+ if (!entry) {
79
+ return null;
80
+ }
81
+ return { task: { ...entry.task }, history: [...entry.history] };
82
+ }
83
+ async save({ agentId, data }) {
84
+ const key = `${agentId}-${data.task.id}`;
85
+ if (!data.task.id) {
86
+ throw new Error("Task ID is required");
87
+ }
88
+ this.store.set(key, {
89
+ task: { ...data.task },
90
+ history: [...data.history]
91
+ });
92
+ }
93
+ };
94
+
95
+ // src/server/a2a/tasks.ts
96
+ function isTaskStatusUpdate(update) {
97
+ return "state" in update && !("parts" in update);
98
+ }
99
+ function isArtifactUpdate(update) {
100
+ return "parts" in update;
101
+ }
102
+ function applyUpdateToTaskAndHistory(current, update) {
103
+ let newTask = structuredClone(current.task);
104
+ let newHistory = structuredClone(current.history);
105
+ if (isTaskStatusUpdate(update)) {
106
+ newTask.status = {
107
+ ...newTask.status,
108
+ // Keep existing properties if not overwritten
109
+ ...update,
110
+ // Apply updates
111
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
112
+ };
113
+ if (update.message?.role === "agent") {
114
+ newHistory.push(update.message);
115
+ }
116
+ } else if (isArtifactUpdate(update)) {
117
+ if (!newTask.artifacts) {
118
+ newTask.artifacts = [];
119
+ } else {
120
+ newTask.artifacts = [...newTask.artifacts];
121
+ }
122
+ const existingIndex = update.index ?? -1;
123
+ let replaced = false;
124
+ if (existingIndex >= 0 && existingIndex < newTask.artifacts.length) {
125
+ const existingArtifact = newTask.artifacts[existingIndex];
126
+ if (update.append) {
127
+ const appendedArtifact = JSON.parse(JSON.stringify(existingArtifact));
128
+ appendedArtifact.parts.push(...update.parts);
129
+ if (update.metadata) {
130
+ appendedArtifact.metadata = {
131
+ ...appendedArtifact.metadata || {},
132
+ ...update.metadata
133
+ };
134
+ }
135
+ if (update.lastChunk !== void 0) appendedArtifact.lastChunk = update.lastChunk;
136
+ if (update.description) appendedArtifact.description = update.description;
137
+ newTask.artifacts[existingIndex] = appendedArtifact;
138
+ replaced = true;
139
+ } else {
140
+ newTask.artifacts[existingIndex] = { ...update };
141
+ replaced = true;
142
+ }
143
+ } else if (update.name) {
144
+ const namedIndex = newTask.artifacts.findIndex((a) => a.name === update.name);
145
+ if (namedIndex >= 0) {
146
+ newTask.artifacts[namedIndex] = { ...update };
147
+ replaced = true;
148
+ }
149
+ }
150
+ if (!replaced) {
151
+ newTask.artifacts.push({ ...update });
152
+ if (newTask.artifacts.some((a) => a.index !== void 0)) {
153
+ newTask.artifacts.sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
154
+ }
155
+ }
156
+ }
157
+ return { task: newTask, history: newHistory };
158
+ }
159
+ async function loadOrCreateTaskAndHistory({
160
+ agentId,
161
+ taskId,
162
+ taskStore,
163
+ message,
164
+ sessionId,
165
+ metadata,
166
+ logger
167
+ }) {
168
+ const data = await taskStore.load({ agentId, taskId });
169
+ if (!data) {
170
+ const initialTask = {
171
+ id: taskId,
172
+ sessionId,
173
+ status: {
174
+ state: "submitted",
175
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
176
+ message: null
177
+ },
178
+ artifacts: [],
179
+ metadata
180
+ };
181
+ const initialData = {
182
+ task: initialTask,
183
+ history: [message]
184
+ };
185
+ logger?.info(`[Task ${taskId}] Created new task and history.`);
186
+ await taskStore.save({ agentId, data: initialData });
187
+ return initialData;
188
+ }
189
+ logger?.info(`[Task ${taskId}] Loaded existing task and history.`);
190
+ let updatedData = {
191
+ task: data.task,
192
+ history: [...data.history, message]
193
+ };
194
+ const { status } = data.task;
195
+ const finalStates = ["completed", "failed", "canceled"];
196
+ if (finalStates.includes(status.state)) {
197
+ logger?.warn(`[Task ${taskId}] Received message for task in final state ${status.state}. Restarting.`);
198
+ updatedData = applyUpdateToTaskAndHistory(updatedData, {
199
+ state: "submitted",
200
+ message: null
201
+ });
202
+ } else if (status.state === "input-required") {
203
+ logger?.info(`[Task ${taskId}] Changing state from 'input-required' to 'working'.`);
204
+ updatedData = applyUpdateToTaskAndHistory(updatedData, { state: "working" });
205
+ } else if (status.state === "working") {
206
+ logger?.warn(`[Task ${taskId}] Received message while already 'working'. Proceeding.`);
207
+ }
208
+ await taskStore.save({ agentId, data: updatedData });
209
+ return {
210
+ task: { ...updatedData.task },
211
+ history: [...updatedData.history]
212
+ };
213
+ }
214
+ function createTaskContext({
215
+ task,
216
+ userMessage,
217
+ history,
218
+ activeCancellations
219
+ }) {
220
+ return {
221
+ task: structuredClone(task),
222
+ userMessage,
223
+ history: structuredClone(history),
224
+ isCancelled: () => activeCancellations.has(task.id)
225
+ };
226
+ }
227
+
228
+ // src/server/handlers/a2a.ts
229
+ var taskSendParamsSchema = z.object({
230
+ id: z.string().min(1, "Invalid or missing task ID (params.id)."),
231
+ message: z.object({
232
+ parts: z.array(
233
+ z.object({
234
+ type: z.enum(["text"]),
235
+ text: z.string()
236
+ })
237
+ )
238
+ })
239
+ });
240
+ async function getAgentCardByIdHandler({
241
+ mastra,
242
+ agentId,
243
+ executionUrl = `/a2a/${agentId}`,
244
+ provider = {
245
+ organization: "Mastra",
246
+ url: "https://mastra.ai"
247
+ },
248
+ version = "1.0",
249
+ runtimeContext
250
+ }) {
251
+ const agent = mastra.getAgent(agentId);
252
+ if (!agent) {
253
+ throw new Error(`Agent with ID ${agentId} not found`);
254
+ }
255
+ const [instructions, tools] = await Promise.all([
256
+ agent.getInstructions({ runtimeContext }),
257
+ agent.getTools({ runtimeContext })
258
+ ]);
259
+ const agentCard = {
260
+ name: agent.id || agentId,
261
+ description: instructions,
262
+ url: executionUrl,
263
+ provider,
264
+ version,
265
+ capabilities: {
266
+ streaming: true,
267
+ // All agents support streaming
268
+ pushNotifications: false,
269
+ stateTransitionHistory: false
270
+ },
271
+ defaultInputModes: ["text"],
272
+ defaultOutputModes: ["text"],
273
+ // Convert agent tools to skills format for A2A protocol
274
+ skills: Object.entries(tools).map(([toolId, tool]) => ({
275
+ id: toolId,
276
+ name: toolId,
277
+ description: tool.description || `Tool: ${toolId}`,
278
+ // Optional fields
279
+ tags: ["tool"]
280
+ }))
281
+ };
282
+ return agentCard;
283
+ }
284
+ function validateTaskSendParams(params) {
285
+ try {
286
+ taskSendParamsSchema.parse(params);
287
+ } catch (error) {
288
+ if (error instanceof z.ZodError) {
289
+ throw A2AError.invalidParams(error.errors[0].message);
290
+ }
291
+ throw error;
292
+ }
293
+ }
294
+ async function handleTaskSend({
295
+ requestId,
296
+ params,
297
+ taskStore,
298
+ agent,
299
+ logger,
300
+ runtimeContext
301
+ }) {
302
+ validateTaskSendParams(params);
303
+ const agentId = agent.id;
304
+ const { id: taskId, message, sessionId, metadata } = params;
305
+ let currentData = await loadOrCreateTaskAndHistory({
306
+ taskId,
307
+ taskStore,
308
+ agentId,
309
+ message,
310
+ sessionId,
311
+ metadata
312
+ });
313
+ createTaskContext({
314
+ task: currentData.task,
315
+ userMessage: message,
316
+ history: currentData.history,
317
+ activeCancellations: taskStore.activeCancellations
318
+ });
319
+ try {
320
+ const { text } = await agent.generate([convertToCoreMessage(message)], {
321
+ runId: taskId,
322
+ runtimeContext
323
+ });
324
+ currentData = applyUpdateToTaskAndHistory(currentData, {
325
+ state: "completed",
326
+ message: {
327
+ role: "agent",
328
+ parts: [
329
+ {
330
+ type: "text",
331
+ text
332
+ }
333
+ ]
334
+ }
335
+ });
336
+ await taskStore.save({ agentId, data: currentData });
337
+ } catch (handlerError) {
338
+ const failureStatusUpdate = {
339
+ state: "failed",
340
+ message: {
341
+ role: "agent",
342
+ parts: [
343
+ {
344
+ type: "text",
345
+ text: `Handler failed: ${handlerError instanceof Error ? handlerError.message : String(handlerError)}`
346
+ }
347
+ ]
348
+ }
349
+ };
350
+ currentData = applyUpdateToTaskAndHistory(currentData, failureStatusUpdate);
351
+ try {
352
+ await taskStore.save({ agentId, data: currentData });
353
+ } catch (saveError) {
354
+ logger?.error(`Failed to save task ${taskId} after handler error:`, saveError?.message);
355
+ }
356
+ return normalizeError(handlerError, requestId, taskId, logger);
357
+ }
358
+ return createSuccessResponse(requestId, currentData.task);
359
+ }
360
+ async function handleTaskGet({
361
+ requestId,
362
+ taskStore,
363
+ agentId,
364
+ taskId
365
+ }) {
366
+ const task = await taskStore.load({ agentId, taskId });
367
+ if (!task) {
368
+ throw A2AError.taskNotFound(taskId);
369
+ }
370
+ return createSuccessResponse(requestId, task);
371
+ }
372
+ async function* handleTaskSendSubscribe({
373
+ requestId,
374
+ params,
375
+ taskStore,
376
+ agent,
377
+ logger,
378
+ runtimeContext
379
+ }) {
380
+ yield createSuccessResponse(requestId, {
381
+ state: "working",
382
+ message: {
383
+ role: "agent",
384
+ parts: [{ type: "text", text: "Generating response..." }]
385
+ }
386
+ });
387
+ let result;
388
+ try {
389
+ result = await handleTaskSend({
390
+ requestId,
391
+ params,
392
+ taskStore,
393
+ agent,
394
+ runtimeContext,
395
+ logger
396
+ });
397
+ } catch (err) {
398
+ if (!(err instanceof A2AError)) {
399
+ throw err;
400
+ }
401
+ result = createErrorResponse(requestId, err.toJSONRPCError());
402
+ }
403
+ yield result;
404
+ }
405
+ async function handleTaskCancel({
406
+ requestId,
407
+ taskStore,
408
+ agentId,
409
+ taskId,
410
+ logger
411
+ }) {
412
+ let data = await taskStore.load({
413
+ agentId,
414
+ taskId
415
+ });
416
+ if (!data) {
417
+ throw A2AError.taskNotFound(taskId);
418
+ }
419
+ const finalStates = ["completed", "failed", "canceled"];
420
+ if (finalStates.includes(data.task.status.state)) {
421
+ logger?.info(`Task ${taskId} already in final state ${data.task.status.state}, cannot cancel.`);
422
+ return createSuccessResponse(requestId, data.task);
423
+ }
424
+ taskStore.activeCancellations.add(taskId);
425
+ const cancelUpdate = {
426
+ state: "canceled",
427
+ message: {
428
+ role: "agent",
429
+ parts: [{ type: "text", text: "Task cancelled by request." }]
430
+ }
431
+ };
432
+ data = applyUpdateToTaskAndHistory(data, cancelUpdate);
433
+ await taskStore.save({ agentId, data });
434
+ taskStore.activeCancellations.delete(taskId);
435
+ return createSuccessResponse(requestId, data.task);
436
+ }
437
+ async function getAgentExecutionHandler({
438
+ requestId,
439
+ mastra,
440
+ agentId,
441
+ runtimeContext,
442
+ method,
443
+ params,
444
+ taskStore = new InMemoryTaskStore(),
445
+ logger
446
+ }) {
447
+ const agent = mastra.getAgent(agentId);
448
+ let taskId;
449
+ try {
450
+ taskId = params.id;
451
+ switch (method) {
452
+ case "tasks/send": {
453
+ const result2 = await handleTaskSend({
454
+ requestId,
455
+ params,
456
+ taskStore,
457
+ agent,
458
+ runtimeContext
459
+ });
460
+ return result2;
461
+ }
462
+ case "tasks/sendSubscribe":
463
+ const result = await handleTaskSendSubscribe({
464
+ requestId,
465
+ taskStore,
466
+ params,
467
+ agent,
468
+ runtimeContext
469
+ });
470
+ return result;
471
+ case "tasks/get": {
472
+ const result2 = await handleTaskGet({
473
+ requestId,
474
+ taskStore,
475
+ agentId,
476
+ taskId
477
+ });
478
+ return result2;
479
+ }
480
+ case "tasks/cancel": {
481
+ const result2 = await handleTaskCancel({
482
+ requestId,
483
+ taskStore,
484
+ agentId,
485
+ taskId
486
+ });
487
+ return result2;
488
+ }
489
+ default:
490
+ throw A2AError.methodNotFound(method);
491
+ }
492
+ } catch (error) {
493
+ if (error instanceof A2AError && taskId && !error.taskId) {
494
+ error.taskId = taskId;
495
+ }
496
+ return normalizeError(error, requestId, taskId, logger);
497
+ }
498
+ }
499
+
500
+ export { a2a_exports, getAgentCardByIdHandler, getAgentExecutionHandler, handleTaskCancel, handleTaskGet, handleTaskSend, handleTaskSendSubscribe };
@@ -1,7 +1,9 @@
1
- import { stringify, esm_default } from './chunk-VK6FX47H.js';
2
- import { validateBody } from './chunk-L7XE5QTW.js';
3
- import { handleError } from './chunk-3AHQ5RGN.js';
4
- import { __export, HTTPException } from './chunk-TRDNDNGQ.js';
1
+ import { stringify, esm_default } from './chunk-LIVAK2DM.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-MLKGABMK.js';
6
+ import { RuntimeContext } from '@mastra/core/runtime-context';
5
7
 
6
8
  // src/server/handlers/agents.ts
7
9
  var agents_exports = {};
@@ -13,27 +15,35 @@ __export(agents_exports, {
13
15
  getLiveEvalsByAgentIdHandler: () => getLiveEvalsByAgentIdHandler,
14
16
  streamGenerateHandler: () => streamGenerateHandler
15
17
  });
16
- async function getAgentsHandler({ mastra }) {
18
+ async function getAgentsHandler({ mastra, runtimeContext }) {
17
19
  try {
18
20
  const agents = mastra.getAgents();
19
- const serializedAgents = Object.entries(agents).reduce((acc, [_id, _agent]) => {
20
- const agent = _agent;
21
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc2, [key, tool]) => {
22
- const _tool = tool;
23
- acc2[key] = {
24
- ..._tool,
25
- inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
26
- outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
21
+ const serializedAgentsMap = await Promise.all(
22
+ Object.entries(agents).map(async ([id, agent]) => {
23
+ const instructions = await agent.getInstructions({ runtimeContext });
24
+ const tools = await agent.getTools({ runtimeContext });
25
+ const llm = await agent.getLLM({ runtimeContext });
26
+ const serializedAgentTools = Object.entries(tools || {}).reduce((acc, [key, tool]) => {
27
+ const _tool = tool;
28
+ acc[key] = {
29
+ ..._tool,
30
+ inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
31
+ outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
32
+ };
33
+ return acc;
34
+ }, {});
35
+ return {
36
+ id,
37
+ name: agent.name,
38
+ instructions,
39
+ tools: serializedAgentTools,
40
+ provider: llm?.getProvider(),
41
+ modelId: llm?.getModelId()
27
42
  };
28
- return acc2;
29
- }, {});
30
- acc[_id] = {
31
- name: agent.name,
32
- instructions: agent.instructions,
33
- tools: serializedAgentTools,
34
- provider: agent.llm?.getProvider(),
35
- modelId: agent.llm?.getModelId()
36
- };
43
+ })
44
+ );
45
+ const serializedAgents = serializedAgentsMap.reduce((acc, { id, ...rest }) => {
46
+ acc[id] = rest;
37
47
  return acc;
38
48
  }, {});
39
49
  return serializedAgents;
@@ -41,13 +51,18 @@ async function getAgentsHandler({ mastra }) {
41
51
  return handleError(error, "Error getting agents");
42
52
  }
43
53
  }
44
- async function getAgentByIdHandler({ mastra, agentId }) {
54
+ async function getAgentByIdHandler({
55
+ mastra,
56
+ runtimeContext,
57
+ agentId
58
+ }) {
45
59
  try {
46
60
  const agent = mastra.getAgent(agentId);
47
61
  if (!agent) {
48
62
  throw new HTTPException(404, { message: "Agent not found" });
49
63
  }
50
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc, [key, tool]) => {
64
+ const tools = await agent.getTools({ runtimeContext });
65
+ const serializedAgentTools = Object.entries(tools || {}).reduce((acc, [key, tool]) => {
51
66
  const _tool = tool;
52
67
  acc[key] = {
53
68
  ..._tool,
@@ -56,39 +71,51 @@ async function getAgentByIdHandler({ mastra, agentId }) {
56
71
  };
57
72
  return acc;
58
73
  }, {});
74
+ const instructions = await agent.getInstructions({ runtimeContext });
75
+ const llm = await agent.getLLM({ runtimeContext });
59
76
  return {
60
77
  name: agent.name,
61
- instructions: agent.instructions,
78
+ instructions,
62
79
  tools: serializedAgentTools,
63
- provider: agent.llm?.getProvider(),
64
- modelId: agent.llm?.getModelId()
80
+ provider: llm?.getProvider(),
81
+ modelId: llm?.getModelId()
65
82
  };
66
83
  } catch (error) {
67
84
  return handleError(error, "Error getting agent");
68
85
  }
69
86
  }
70
- async function getEvalsByAgentIdHandler({ mastra, agentId }) {
87
+ async function getEvalsByAgentIdHandler({
88
+ mastra,
89
+ runtimeContext,
90
+ agentId
91
+ }) {
71
92
  try {
72
93
  const agent = mastra.getAgent(agentId);
73
- const evals = await mastra.getStorage()?.__getEvalsByAgentName?.(agent.name, "test") || [];
94
+ const evals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "test") || [];
95
+ const instructions = await agent.getInstructions({ runtimeContext });
74
96
  return {
75
97
  id: agentId,
76
98
  name: agent.name,
77
- instructions: agent.instructions,
99
+ instructions,
78
100
  evals
79
101
  };
80
102
  } catch (error) {
81
103
  return handleError(error, "Error getting test evals");
82
104
  }
83
105
  }
84
- async function getLiveEvalsByAgentIdHandler({ mastra, agentId }) {
106
+ async function getLiveEvalsByAgentIdHandler({
107
+ mastra,
108
+ runtimeContext,
109
+ agentId
110
+ }) {
85
111
  try {
86
112
  const agent = mastra.getAgent(agentId);
87
- const evals = await mastra.getStorage()?.__getEvalsByAgentName?.(agent.name, "live") || [];
113
+ const evals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "live") || [];
114
+ const instructions = await agent.getInstructions({ runtimeContext });
88
115
  return {
89
116
  id: agentId,
90
117
  name: agent.name,
91
- instructions: agent.instructions,
118
+ instructions,
92
119
  evals
93
120
  };
94
121
  } catch (error) {
@@ -97,6 +124,7 @@ async function getLiveEvalsByAgentIdHandler({ mastra, agentId }) {
97
124
  }
98
125
  async function generateHandler({
99
126
  mastra,
127
+ runtimeContext,
100
128
  agentId,
101
129
  body
102
130
  }) {
@@ -105,13 +133,18 @@ async function generateHandler({
105
133
  if (!agent) {
106
134
  throw new HTTPException(404, { message: "Agent not found" });
107
135
  }
108
- const { messages, resourceId, resourceid, ...rest } = body;
136
+ const { messages, resourceId, resourceid, runtimeContext: agentRuntimeContext, ...rest } = body;
109
137
  const finalResourceId = resourceId ?? resourceid;
138
+ const finalRuntimeContext = new RuntimeContext([
139
+ ...Array.from(runtimeContext.entries()),
140
+ ...Array.from(Object.entries(agentRuntimeContext ?? {}))
141
+ ]);
110
142
  validateBody({ messages });
111
143
  const result = await agent.generate(messages, {
112
144
  ...rest,
113
145
  // @ts-expect-error TODO fix types
114
- resourceId: finalResourceId
146
+ resourceId: finalResourceId,
147
+ runtimeContext: finalRuntimeContext
115
148
  });
116
149
  return result;
117
150
  } catch (error) {
@@ -120,6 +153,7 @@ async function generateHandler({
120
153
  }
121
154
  async function streamGenerateHandler({
122
155
  mastra,
156
+ runtimeContext,
123
157
  agentId,
124
158
  body
125
159
  }) {
@@ -128,13 +162,18 @@ async function streamGenerateHandler({
128
162
  if (!agent) {
129
163
  throw new HTTPException(404, { message: "Agent not found" });
130
164
  }
131
- const { messages, resourceId, resourceid, ...rest } = body;
165
+ const { messages, resourceId, resourceid, runtimeContext: agentRuntimeContext, ...rest } = body;
132
166
  const finalResourceId = resourceId ?? resourceid;
167
+ const finalRuntimeContext = new RuntimeContext([
168
+ ...Array.from(runtimeContext.entries()),
169
+ ...Array.from(Object.entries(agentRuntimeContext ?? {}))
170
+ ]);
133
171
  validateBody({ messages });
134
172
  const streamResult = await agent.stream(messages, {
135
173
  ...rest,
136
174
  // @ts-expect-error TODO fix types
137
- resourceId: finalResourceId
175
+ resourceId: finalResourceId,
176
+ runtimeContext: finalRuntimeContext
138
177
  });
139
178
  const streamResponse = rest.output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
140
179
  sendUsage: true,