@mastra/server 0.0.1-alpha.6 → 0.10.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.
- package/{LICENSE → LICENSE.md} +3 -1
- package/README.md +48 -135
- package/dist/_tsup-dts-rollup.d.cts +305 -52
- package/dist/_tsup-dts-rollup.d.ts +305 -52
- package/dist/{chunk-4JINXASC.js → chunk-55DOQLP6.js} +5 -4
- package/dist/{chunk-QN4KF3BH.cjs → chunk-57CJTIPW.cjs} +2 -2
- package/dist/chunk-5SN4U5AC.cjs +508 -0
- package/dist/{chunk-ZLBRQFDD.cjs → chunk-64U3UDTH.cjs} +2 -2
- package/dist/chunk-6B4OMWT6.cjs +343 -0
- package/dist/chunk-75ZPJI57.cjs +9 -0
- package/dist/{chunk-VB7KH62D.cjs → chunk-7DLZLWJV.cjs} +16 -12
- package/dist/{chunk-M56ECCHK.cjs → chunk-BNEY4P4P.cjs} +20 -19
- package/dist/{chunk-2YONKUWB.js → chunk-C7564HUT.js} +58 -33
- package/dist/chunk-D4IRYCUI.cjs +235 -0
- package/dist/{chunk-RBQASTUP.js → chunk-DJJIUEL2.js} +13 -5
- package/dist/{chunk-L7XE5QTW.js → chunk-H5PTF3Y4.js} +1 -1
- package/dist/{chunk-3RVHWGWO.js → chunk-HFWCEP5S.js} +6 -12
- package/dist/chunk-LIVAK2DM.js +2001 -0
- package/dist/{chunk-3AHQ5RGN.js → chunk-M5ABIP7D.js} +1 -1
- package/dist/{chunk-CWSDZEZG.cjs → chunk-MHKNLNAN.cjs} +15 -12
- package/dist/chunk-MLKGABMK.js +7 -0
- package/dist/{chunk-TRDNDNGQ.js → chunk-NYN7KFXL.js} +1 -7
- package/dist/{chunk-FV45V6WC.cjs → chunk-OCWPVYNI.cjs} +0 -7
- package/dist/{chunk-DVPP5S6I.js → chunk-OR3CIE2H.js} +9 -6
- package/dist/chunk-P6SCPDYW.js +500 -0
- package/dist/chunk-QY36IPTP.js +331 -0
- package/dist/{chunk-YNSGUC2O.js → chunk-TJKLBTFB.js} +23 -7
- package/dist/chunk-VPNDC2DI.cjs +148 -0
- package/dist/{chunk-ILW7XYNJ.js → chunk-W7VCKPAD.js} +84 -60
- package/dist/{chunk-2JQC6JWP.js → chunk-WFBJJNCK.js} +10 -6
- package/dist/chunk-WUC6LSTW.js +227 -0
- package/dist/{chunk-2FJURXCL.cjs → chunk-Y7UWRW5X.cjs} +43 -35
- package/dist/{chunk-A7DF4ETD.cjs → chunk-YBVOQN4M.cjs} +22 -28
- package/dist/chunk-YIOVBYZH.cjs +332 -0
- package/dist/chunk-YWLUOY3D.cjs +2004 -0
- package/dist/{chunk-4C3EPMMF.cjs → chunk-ZE5AAC4I.cjs} +40 -24
- package/dist/server/handlers/a2a.cjs +30 -0
- package/dist/server/handlers/a2a.d.cts +6 -0
- package/dist/server/handlers/a2a.d.ts +6 -0
- package/dist/server/handlers/a2a.js +1 -0
- package/dist/server/handlers/agents.cjs +7 -7
- package/dist/server/handlers/agents.js +1 -1
- package/dist/server/handlers/error.cjs +2 -2
- package/dist/server/handlers/error.js +1 -1
- package/dist/server/handlers/legacyWorkflows.cjs +46 -0
- package/dist/server/handlers/legacyWorkflows.d.cts +10 -0
- package/dist/server/handlers/legacyWorkflows.d.ts +10 -0
- package/dist/server/handlers/legacyWorkflows.js +1 -0
- package/dist/server/handlers/logs.cjs +4 -4
- package/dist/server/handlers/logs.js +1 -1
- package/dist/server/handlers/memory.cjs +9 -9
- package/dist/server/handlers/memory.js +1 -1
- package/dist/server/handlers/network.cjs +5 -5
- package/dist/server/handlers/network.js +1 -1
- package/dist/server/handlers/telemetry.cjs +3 -3
- package/dist/server/handlers/telemetry.js +1 -1
- package/dist/server/handlers/tools.cjs +5 -5
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/utils.cjs +2 -2
- package/dist/server/handlers/utils.js +1 -1
- package/dist/server/handlers/vector.cjs +7 -7
- package/dist/server/handlers/vector.js +1 -1
- package/dist/server/handlers/voice.cjs +4 -4
- package/dist/server/handlers/voice.js +1 -1
- package/dist/server/handlers/workflows.cjs +13 -13
- package/dist/server/handlers/workflows.d.cts +2 -2
- package/dist/server/handlers/workflows.d.ts +2 -2
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/handlers.cjs +33 -23
- package/dist/server/handlers.d.cts +2 -0
- package/dist/server/handlers.d.ts +2 -0
- package/dist/server/handlers.js +11 -9
- package/package.json +9 -7
- package/dist/chunk-5JOF627H.cjs +0 -123
- package/dist/chunk-BMA2ORRT.js +0 -152
- package/dist/chunk-GV52BII2.cjs +0 -160
- package/dist/chunk-QH6XWSXP.cjs +0 -5579
- package/dist/chunk-VK6FX47H.js +0 -5576
- package/dist/chunk-X37I6GZT.cjs +0 -308
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunk64U3UDTH_cjs = require('./chunk-64U3UDTH.cjs');
|
|
4
|
+
var chunkOCWPVYNI_cjs = require('./chunk-OCWPVYNI.cjs');
|
|
5
|
+
var chunk75ZPJI57_cjs = require('./chunk-75ZPJI57.cjs');
|
|
5
6
|
|
|
6
7
|
// src/server/handlers/telemetry.ts
|
|
7
8
|
var telemetry_exports = {};
|
|
8
|
-
|
|
9
|
+
chunk75ZPJI57_cjs.__export(telemetry_exports, {
|
|
9
10
|
getTelemetryHandler: () => getTelemetryHandler,
|
|
10
11
|
storeTelemetryHandler: () => storeTelemetryHandler
|
|
11
12
|
});
|
|
@@ -14,31 +15,33 @@ async function getTelemetryHandler({ mastra, body }) {
|
|
|
14
15
|
const telemetry = mastra.getTelemetry();
|
|
15
16
|
const storage = mastra.getStorage();
|
|
16
17
|
if (!telemetry) {
|
|
17
|
-
throw new
|
|
18
|
+
throw new chunkOCWPVYNI_cjs.HTTPException(400, { message: "Telemetry is not initialized" });
|
|
18
19
|
}
|
|
19
20
|
if (!storage) {
|
|
20
|
-
throw new
|
|
21
|
+
throw new chunkOCWPVYNI_cjs.HTTPException(400, { message: "Storage is not initialized" });
|
|
21
22
|
}
|
|
22
23
|
if (!body) {
|
|
23
|
-
throw new
|
|
24
|
+
throw new chunkOCWPVYNI_cjs.HTTPException(400, { message: "Body is required" });
|
|
24
25
|
}
|
|
25
|
-
const { name, scope, page, perPage, attribute } = body;
|
|
26
|
+
const { name, scope, page, perPage, attribute, fromDate, toDate } = body;
|
|
26
27
|
const attributes = attribute ? Object.fromEntries(
|
|
27
28
|
(Array.isArray(attribute) ? attribute : [attribute]).map((attr) => {
|
|
28
29
|
const [key, value] = attr.split(":");
|
|
29
30
|
return [key, value];
|
|
30
31
|
})
|
|
31
32
|
) : void 0;
|
|
32
|
-
const traces = await storage.
|
|
33
|
+
const traces = await storage.getTraces({
|
|
33
34
|
name,
|
|
34
35
|
scope,
|
|
35
36
|
page: Number(page ?? 0),
|
|
36
37
|
perPage: Number(perPage ?? 100),
|
|
37
|
-
attributes
|
|
38
|
+
attributes,
|
|
39
|
+
fromDate: fromDate ? new Date(fromDate) : void 0,
|
|
40
|
+
toDate: toDate ? new Date(toDate) : void 0
|
|
38
41
|
});
|
|
39
42
|
return traces;
|
|
40
43
|
} catch (error2) {
|
|
41
|
-
return
|
|
44
|
+
return chunk64U3UDTH_cjs.handleError(error2, "Error getting telemetry");
|
|
42
45
|
}
|
|
43
46
|
}
|
|
44
47
|
async function storeTelemetryHandler({ mastra, body }) {
|
|
@@ -46,7 +49,7 @@ async function storeTelemetryHandler({ mastra, body }) {
|
|
|
46
49
|
const storage = mastra.getStorage();
|
|
47
50
|
const logger = mastra.getLogger();
|
|
48
51
|
if (!storage) {
|
|
49
|
-
throw new
|
|
52
|
+
throw new chunkOCWPVYNI_cjs.HTTPException(400, { message: "Storage is not initialized" });
|
|
50
53
|
}
|
|
51
54
|
const now = /* @__PURE__ */ new Date();
|
|
52
55
|
const items = body?.resourceSpans?.[0]?.scopeSpans;
|
|
@@ -107,7 +110,7 @@ async function storeTelemetryHandler({ mastra, body }) {
|
|
|
107
110
|
}
|
|
108
111
|
return acc;
|
|
109
112
|
}, []);
|
|
110
|
-
return storage.
|
|
113
|
+
return storage.batchTraceInsert({
|
|
111
114
|
records: allSpans
|
|
112
115
|
}).then(() => {
|
|
113
116
|
return {
|
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __export = (target, all) => {
|
|
3
|
-
for (var name in all)
|
|
4
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
-
};
|
|
6
|
-
|
|
7
1
|
// src/server/http-exception.ts
|
|
8
2
|
var HTTPException = class extends Error {
|
|
9
3
|
res;
|
|
@@ -37,4 +31,4 @@ var HTTPException = class extends Error {
|
|
|
37
31
|
}
|
|
38
32
|
};
|
|
39
33
|
|
|
40
|
-
export { HTTPException
|
|
34
|
+
export { HTTPException };
|
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __export = (target, all) => {
|
|
5
|
-
for (var name in all)
|
|
6
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
7
|
-
};
|
|
8
|
-
|
|
9
3
|
// src/server/http-exception.ts
|
|
10
4
|
var HTTPException = class extends Error {
|
|
11
5
|
res;
|
|
@@ -40,4 +34,3 @@ var HTTPException = class extends Error {
|
|
|
40
34
|
};
|
|
41
35
|
|
|
42
36
|
exports.HTTPException = HTTPException;
|
|
43
|
-
exports.__export = __export;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { handleError } from './chunk-
|
|
2
|
-
import {
|
|
1
|
+
import { handleError } from './chunk-M5ABIP7D.js';
|
|
2
|
+
import { HTTPException } from './chunk-NYN7KFXL.js';
|
|
3
|
+
import { __export } from './chunk-MLKGABMK.js';
|
|
3
4
|
|
|
4
5
|
// src/server/handlers/telemetry.ts
|
|
5
6
|
var telemetry_exports = {};
|
|
@@ -20,19 +21,21 @@ async function getTelemetryHandler({ mastra, body }) {
|
|
|
20
21
|
if (!body) {
|
|
21
22
|
throw new HTTPException(400, { message: "Body is required" });
|
|
22
23
|
}
|
|
23
|
-
const { name, scope, page, perPage, attribute } = body;
|
|
24
|
+
const { name, scope, page, perPage, attribute, fromDate, toDate } = body;
|
|
24
25
|
const attributes = attribute ? Object.fromEntries(
|
|
25
26
|
(Array.isArray(attribute) ? attribute : [attribute]).map((attr) => {
|
|
26
27
|
const [key, value] = attr.split(":");
|
|
27
28
|
return [key, value];
|
|
28
29
|
})
|
|
29
30
|
) : void 0;
|
|
30
|
-
const traces = await storage.
|
|
31
|
+
const traces = await storage.getTraces({
|
|
31
32
|
name,
|
|
32
33
|
scope,
|
|
33
34
|
page: Number(page ?? 0),
|
|
34
35
|
perPage: Number(perPage ?? 100),
|
|
35
|
-
attributes
|
|
36
|
+
attributes,
|
|
37
|
+
fromDate: fromDate ? new Date(fromDate) : void 0,
|
|
38
|
+
toDate: toDate ? new Date(toDate) : void 0
|
|
36
39
|
});
|
|
37
40
|
return traces;
|
|
38
41
|
} catch (error2) {
|
|
@@ -105,7 +108,7 @@ async function storeTelemetryHandler({ mastra, body }) {
|
|
|
105
108
|
}
|
|
106
109
|
return acc;
|
|
107
110
|
}, []);
|
|
108
|
-
return storage.
|
|
111
|
+
return storage.batchTraceInsert({
|
|
109
112
|
records: allSpans
|
|
110
113
|
}).then(() => {
|
|
111
114
|
return {
|
|
@@ -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 };
|