@mastra/server 0.0.1-alpha.6 → 0.10.1-alpha.0

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 (79) hide show
  1. package/{LICENSE → LICENSE.md} +3 -1
  2. package/README.md +48 -135
  3. package/dist/_tsup-dts-rollup.d.cts +316 -52
  4. package/dist/_tsup-dts-rollup.d.ts +316 -52
  5. package/dist/{chunk-4JINXASC.js → chunk-55DOQLP6.js} +5 -4
  6. package/dist/{chunk-QN4KF3BH.cjs → chunk-57CJTIPW.cjs} +2 -2
  7. package/dist/chunk-5SN4U5AC.cjs +508 -0
  8. package/dist/{chunk-ZLBRQFDD.cjs → chunk-64U3UDTH.cjs} +2 -2
  9. package/dist/chunk-75ZPJI57.cjs +9 -0
  10. package/dist/{chunk-VB7KH62D.cjs → chunk-7DLZLWJV.cjs} +16 -12
  11. package/dist/{chunk-M56ECCHK.cjs → chunk-BNEY4P4P.cjs} +20 -19
  12. package/dist/{chunk-2YONKUWB.js → chunk-C7564HUT.js} +58 -33
  13. package/dist/chunk-D4IRYCUI.cjs +235 -0
  14. package/dist/{chunk-RBQASTUP.js → chunk-DJJIUEL2.js} +13 -5
  15. package/dist/{chunk-L7XE5QTW.js → chunk-H5PTF3Y4.js} +1 -1
  16. package/dist/{chunk-3RVHWGWO.js → chunk-HFWCEP5S.js} +6 -12
  17. package/dist/chunk-KUNQFY2W.js +365 -0
  18. package/dist/chunk-LIVAK2DM.js +2001 -0
  19. package/dist/{chunk-3AHQ5RGN.js → chunk-M5ABIP7D.js} +1 -1
  20. package/dist/{chunk-CWSDZEZG.cjs → chunk-MHKNLNAN.cjs} +15 -12
  21. package/dist/chunk-MLKGABMK.js +7 -0
  22. package/dist/chunk-MMO2HDM6.cjs +378 -0
  23. package/dist/{chunk-TRDNDNGQ.js → chunk-NYN7KFXL.js} +1 -7
  24. package/dist/{chunk-FV45V6WC.cjs → chunk-OCWPVYNI.cjs} +0 -7
  25. package/dist/{chunk-DVPP5S6I.js → chunk-OR3CIE2H.js} +9 -6
  26. package/dist/chunk-P6SCPDYW.js +500 -0
  27. package/dist/{chunk-YNSGUC2O.js → chunk-TJKLBTFB.js} +23 -7
  28. package/dist/chunk-VPNDC2DI.cjs +148 -0
  29. package/dist/{chunk-ILW7XYNJ.js → chunk-W7VCKPAD.js} +84 -60
  30. package/dist/{chunk-2JQC6JWP.js → chunk-WFBJJNCK.js} +10 -6
  31. package/dist/chunk-WUC6LSTW.js +227 -0
  32. package/dist/{chunk-2FJURXCL.cjs → chunk-Y7UWRW5X.cjs} +43 -35
  33. package/dist/{chunk-A7DF4ETD.cjs → chunk-YBVOQN4M.cjs} +22 -28
  34. package/dist/chunk-YIOVBYZH.cjs +332 -0
  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/legacyWorkflows.cjs +46 -0
  46. package/dist/server/handlers/legacyWorkflows.d.cts +10 -0
  47. package/dist/server/handlers/legacyWorkflows.d.ts +10 -0
  48. package/dist/server/handlers/legacyWorkflows.js +1 -0
  49. package/dist/server/handlers/logs.cjs +4 -4
  50. package/dist/server/handlers/logs.js +1 -1
  51. package/dist/server/handlers/memory.cjs +9 -9
  52. package/dist/server/handlers/memory.js +1 -1
  53. package/dist/server/handlers/network.cjs +5 -5
  54. package/dist/server/handlers/network.js +1 -1
  55. package/dist/server/handlers/telemetry.cjs +3 -3
  56. package/dist/server/handlers/telemetry.js +1 -1
  57. package/dist/server/handlers/tools.cjs +5 -5
  58. package/dist/server/handlers/tools.js +1 -1
  59. package/dist/server/handlers/utils.cjs +2 -2
  60. package/dist/server/handlers/utils.js +1 -1
  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 +17 -13
  66. package/dist/server/handlers/workflows.d.cts +3 -2
  67. package/dist/server/handlers/workflows.d.ts +3 -2
  68. package/dist/server/handlers/workflows.js +1 -1
  69. package/dist/server/handlers.cjs +33 -23
  70. package/dist/server/handlers.d.cts +2 -0
  71. package/dist/server/handlers.d.ts +2 -0
  72. package/dist/server/handlers.js +11 -9
  73. package/package.json +9 -7
  74. package/dist/chunk-5JOF627H.cjs +0 -123
  75. package/dist/chunk-BMA2ORRT.js +0 -152
  76. package/dist/chunk-GV52BII2.cjs +0 -160
  77. package/dist/chunk-QH6XWSXP.cjs +0 -5579
  78. package/dist/chunk-VK6FX47H.js +0 -5576
  79. package/dist/chunk-X37I6GZT.cjs +0 -308
@@ -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/di';
5
7
  import { isVercelTool } from '@mastra/core/tools';
6
8
 
7
9
  // src/server/handlers/tools.ts
@@ -55,7 +57,9 @@ function executeToolHandler(tools) {
55
57
  mastra,
56
58
  runId,
57
59
  toolId,
58
- data
60
+ data,
61
+ runtimeContext,
62
+ runtimeContextFromRequest
59
63
  }) => {
60
64
  try {
61
65
  if (!toolId) {
@@ -73,10 +77,15 @@ function executeToolHandler(tools) {
73
77
  const result2 = await tool.execute(data);
74
78
  return result2;
75
79
  }
80
+ const finalRuntimeContext = new RuntimeContext([
81
+ ...Array.from(runtimeContext.entries()),
82
+ ...Array.from(Object.entries(runtimeContextFromRequest ?? {}))
83
+ ]);
76
84
  const result = await tool.execute({
77
85
  context: data,
78
86
  mastra,
79
- runId
87
+ runId,
88
+ runtimeContext: finalRuntimeContext
80
89
  });
81
90
  return result;
82
91
  } catch (error) {
@@ -88,7 +97,9 @@ async function executeAgentToolHandler({
88
97
  mastra,
89
98
  agentId,
90
99
  toolId,
91
- data
100
+ data,
101
+ runtimeContext,
102
+ runtimeContextFromRequest
92
103
  }) {
93
104
  try {
94
105
  const agent = agentId ? mastra.getAgent(agentId) : null;
@@ -102,8 +113,13 @@ async function executeAgentToolHandler({
102
113
  if (!tool?.execute) {
103
114
  throw new HTTPException(400, { message: "Tool is not executable" });
104
115
  }
116
+ const finalRuntimeContext = new RuntimeContext([
117
+ ...Array.from(runtimeContext.entries()),
118
+ ...Array.from(Object.entries(runtimeContextFromRequest ?? {}))
119
+ ]);
105
120
  const result = await tool.execute({
106
121
  context: data,
122
+ runtimeContext: finalRuntimeContext,
107
123
  mastra,
108
124
  runId: agentId
109
125
  });
@@ -0,0 +1,148 @@
1
+ 'use strict';
2
+
3
+ var chunk57CJTIPW_cjs = require('./chunk-57CJTIPW.cjs');
4
+ var chunk64U3UDTH_cjs = require('./chunk-64U3UDTH.cjs');
5
+ var chunkOCWPVYNI_cjs = require('./chunk-OCWPVYNI.cjs');
6
+ var chunk75ZPJI57_cjs = require('./chunk-75ZPJI57.cjs');
7
+
8
+ // src/server/handlers/network.ts
9
+ var network_exports = {};
10
+ chunk75ZPJI57_cjs.__export(network_exports, {
11
+ generateHandler: () => generateHandler,
12
+ getNetworkByIdHandler: () => getNetworkByIdHandler,
13
+ getNetworksHandler: () => getNetworksHandler,
14
+ streamGenerateHandler: () => streamGenerateHandler
15
+ });
16
+ async function getNetworksHandler({
17
+ mastra,
18
+ runtimeContext
19
+ }) {
20
+ try {
21
+ const networks = mastra.getNetworks();
22
+ const serializedNetworks = await Promise.all(
23
+ networks.map(async (network) => {
24
+ const routingAgent = network.getRoutingAgent();
25
+ const routingLLM = await routingAgent.getLLM({ runtimeContext });
26
+ const agents = network.getAgents();
27
+ return {
28
+ id: network.formatAgentId(routingAgent.name),
29
+ name: routingAgent.name,
30
+ instructions: routingAgent.instructions,
31
+ agents: await Promise.all(
32
+ agents.map(async (agent) => {
33
+ const llm = await agent.getLLM({ runtimeContext });
34
+ return {
35
+ name: agent.name,
36
+ provider: llm?.getProvider(),
37
+ modelId: llm?.getModelId()
38
+ };
39
+ })
40
+ ),
41
+ routingModel: {
42
+ provider: routingLLM?.getProvider(),
43
+ modelId: routingLLM?.getModelId()
44
+ }
45
+ };
46
+ })
47
+ );
48
+ return serializedNetworks;
49
+ } catch (error) {
50
+ return chunk64U3UDTH_cjs.handleError(error, "Error getting networks");
51
+ }
52
+ }
53
+ async function getNetworkByIdHandler({
54
+ mastra,
55
+ networkId,
56
+ runtimeContext
57
+ }) {
58
+ try {
59
+ const networks = mastra.getNetworks();
60
+ const network = networks.find((network2) => {
61
+ const routingAgent2 = network2.getRoutingAgent();
62
+ return network2.formatAgentId(routingAgent2.name) === networkId;
63
+ });
64
+ if (!network) {
65
+ throw new chunkOCWPVYNI_cjs.HTTPException(404, { message: "Network not found" });
66
+ }
67
+ const routingAgent = network.getRoutingAgent();
68
+ const routingLLM = await routingAgent.getLLM({ runtimeContext });
69
+ const agents = network.getAgents();
70
+ const serializedNetwork = {
71
+ id: network.formatAgentId(routingAgent.name),
72
+ name: routingAgent.name,
73
+ instructions: routingAgent.instructions,
74
+ agents: await Promise.all(
75
+ agents.map(async (agent) => {
76
+ const llm = await agent.getLLM({ runtimeContext });
77
+ return {
78
+ name: agent.name,
79
+ provider: llm?.getProvider(),
80
+ modelId: llm?.getModelId()
81
+ };
82
+ })
83
+ ),
84
+ routingModel: {
85
+ provider: routingLLM?.getProvider(),
86
+ modelId: routingLLM?.getModelId()
87
+ }
88
+ };
89
+ return serializedNetwork;
90
+ } catch (error) {
91
+ return chunk64U3UDTH_cjs.handleError(error, "Error getting network by ID");
92
+ }
93
+ }
94
+ async function generateHandler({
95
+ mastra,
96
+ runtimeContext,
97
+ networkId,
98
+ body
99
+ }) {
100
+ try {
101
+ const network = mastra.getNetwork(networkId);
102
+ if (!network) {
103
+ throw new chunkOCWPVYNI_cjs.HTTPException(404, { message: "Network not found" });
104
+ }
105
+ chunk57CJTIPW_cjs.validateBody({ messages: body.messages });
106
+ const { messages, ...rest } = body;
107
+ const result = await network.generate(messages, { ...rest, runtimeContext });
108
+ return result;
109
+ } catch (error) {
110
+ return chunk64U3UDTH_cjs.handleError(error, "Error generating from network");
111
+ }
112
+ }
113
+ async function streamGenerateHandler({
114
+ mastra,
115
+ networkId,
116
+ body,
117
+ runtimeContext
118
+ }) {
119
+ try {
120
+ const network = mastra.getNetwork(networkId);
121
+ if (!network) {
122
+ throw new chunkOCWPVYNI_cjs.HTTPException(404, { message: "Network not found" });
123
+ }
124
+ chunk57CJTIPW_cjs.validateBody({ messages: body.messages });
125
+ const { messages, output, ...rest } = body;
126
+ const streamResult = await network.stream(messages, {
127
+ output,
128
+ ...rest,
129
+ runtimeContext
130
+ });
131
+ const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
132
+ sendUsage: true,
133
+ sendReasoning: true,
134
+ getErrorMessage: (error) => {
135
+ return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
136
+ }
137
+ });
138
+ return streamResponse;
139
+ } catch (error) {
140
+ return chunk64U3UDTH_cjs.handleError(error, "Error streaming from network");
141
+ }
142
+ }
143
+
144
+ exports.generateHandler = generateHandler;
145
+ exports.getNetworkByIdHandler = getNetworkByIdHandler;
146
+ exports.getNetworksHandler = getNetworksHandler;
147
+ exports.network_exports = network_exports;
148
+ exports.streamGenerateHandler = streamGenerateHandler;