@mastra/server 0.0.0-fix-thread-list-20251105222841 → 0.0.0-fix-ai-sdk-dependency-20251124104209
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/CHANGELOG.md +417 -3
- package/dist/chunk-2NW6POYK.cjs +89 -0
- package/dist/chunk-2NW6POYK.cjs.map +1 -0
- package/dist/chunk-35NT4TMQ.cjs +201 -0
- package/dist/chunk-35NT4TMQ.cjs.map +1 -0
- package/dist/{chunk-ALOLTNSO.js → chunk-3R5EV3HV.js} +208 -21
- package/dist/chunk-3R5EV3HV.js.map +1 -0
- package/dist/{chunk-XXGID4PQ.cjs → chunk-4ECGVOJZ.cjs} +214 -21
- package/dist/chunk-4ECGVOJZ.cjs.map +1 -0
- package/dist/chunk-5PONYNYP.cjs +125 -0
- package/dist/chunk-5PONYNYP.cjs.map +1 -0
- package/dist/chunk-5W4RPVTK.cjs +49 -0
- package/dist/chunk-5W4RPVTK.cjs.map +1 -0
- package/dist/{chunk-QXWWLCTQ.js → chunk-6BISSAIF.js} +591 -131
- package/dist/chunk-6BISSAIF.js.map +1 -0
- package/dist/chunk-6DTV6NEW.js +116 -0
- package/dist/chunk-6DTV6NEW.js.map +1 -0
- package/dist/chunk-AEO6IHLK.cjs +368 -0
- package/dist/chunk-AEO6IHLK.cjs.map +1 -0
- package/dist/chunk-ASZUOBKV.js +310 -0
- package/dist/chunk-ASZUOBKV.js.map +1 -0
- package/dist/chunk-ECIVTQ4E.js +354 -0
- package/dist/chunk-ECIVTQ4E.js.map +1 -0
- package/dist/chunk-FAQICBMH.js +164 -0
- package/dist/chunk-FAQICBMH.js.map +1 -0
- package/dist/chunk-FXDZLX2Y.js +192 -0
- package/dist/chunk-FXDZLX2Y.js.map +1 -0
- package/dist/{chunk-DNUO33HF.js → chunk-G7BPNX2V.js} +5 -4
- package/dist/chunk-G7BPNX2V.js.map +1 -0
- package/dist/chunk-I5VZ5SKG.js +328 -0
- package/dist/chunk-I5VZ5SKG.js.map +1 -0
- package/dist/chunk-ICANWSEW.js +204 -0
- package/dist/chunk-ICANWSEW.js.map +1 -0
- package/dist/chunk-KB5NSROG.cjs +211 -0
- package/dist/chunk-KB5NSROG.cjs.map +1 -0
- package/dist/chunk-MWQQRVQC.cjs +259 -0
- package/dist/chunk-MWQQRVQC.cjs.map +1 -0
- package/dist/chunk-NDFAQBQD.cjs +792 -0
- package/dist/chunk-NDFAQBQD.cjs.map +1 -0
- package/dist/chunk-PKRHEXX7.js +74 -0
- package/dist/chunk-PKRHEXX7.js.map +1 -0
- package/dist/chunk-QGWCNTG6.cjs +797 -0
- package/dist/chunk-QGWCNTG6.cjs.map +1 -0
- package/dist/chunk-R4M3BSUG.js +226 -0
- package/dist/chunk-R4M3BSUG.js.map +1 -0
- package/dist/{chunk-M6KNPIZZ.cjs → chunk-TBVUN4XN.cjs} +1622 -1159
- package/dist/chunk-TBVUN4XN.cjs.map +1 -0
- package/dist/chunk-UJNHKFBR.cjs +167 -0
- package/dist/chunk-UJNHKFBR.cjs.map +1 -0
- package/dist/chunk-UOFV2ZCI.js +878 -0
- package/dist/chunk-UOFV2ZCI.js.map +1 -0
- package/dist/{chunk-LWLSQ2W4.cjs → chunk-UZ6CYAOG.cjs} +5 -4
- package/dist/chunk-UZ6CYAOG.cjs.map +1 -0
- package/dist/chunk-VQAT5HX6.js +756 -0
- package/dist/chunk-VQAT5HX6.js.map +1 -0
- package/dist/chunk-XWGAT2DA.js +44 -0
- package/dist/chunk-XWGAT2DA.js.map +1 -0
- package/dist/chunk-YJ3VDL3Z.cjs +346 -0
- package/dist/chunk-YJ3VDL3Z.cjs.map +1 -0
- package/dist/chunk-Z36N2OQA.cjs +907 -0
- package/dist/chunk-Z36N2OQA.cjs.map +1 -0
- package/dist/chunk-ZLRTFRL4.js +773 -0
- package/dist/chunk-ZLRTFRL4.js.map +1 -0
- package/dist/chunk-ZODCSH2W.cjs +322 -0
- package/dist/chunk-ZODCSH2W.cjs.map +1 -0
- package/dist/server/handlers/a2a.cjs +15 -7
- package/dist/server/handlers/a2a.d.ts +482 -0
- package/dist/server/handlers/a2a.d.ts.map +1 -1
- package/dist/server/handlers/a2a.js +1 -1
- package/dist/server/handlers/agent-builder.cjs +37 -37
- package/dist/server/handlers/agent-builder.d.ts +594 -77
- package/dist/server/handlers/agent-builder.d.ts.map +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/agents.cjs +53 -37
- package/dist/server/handlers/agents.d.ts +3271 -128
- package/dist/server/handlers/agents.d.ts.map +1 -1
- package/dist/server/handlers/agents.js +1 -1
- package/dist/server/handlers/logs.cjs +7 -7
- package/dist/server/handlers/logs.d.ts +135 -27
- package/dist/server/handlers/logs.d.ts.map +1 -1
- package/dist/server/handlers/logs.js +1 -1
- package/dist/server/handlers/memory.cjs +67 -27
- package/dist/server/handlers/memory.d.ts +933 -96
- package/dist/server/handlers/memory.d.ts.map +1 -1
- package/dist/server/handlers/memory.js +1 -1
- package/dist/server/handlers/observability.cjs +23 -7
- package/dist/server/handlers/observability.d.ts +124 -17
- package/dist/server/handlers/observability.d.ts.map +1 -1
- package/dist/server/handlers/observability.js +1 -1
- package/dist/server/handlers/scores.cjs +13 -13
- package/dist/server/handlers/scores.d.ts +110 -141
- package/dist/server/handlers/scores.d.ts.map +1 -1
- package/dist/server/handlers/scores.js +1 -1
- package/dist/server/handlers/test-utils.cjs +15 -0
- package/dist/server/handlers/test-utils.cjs.map +1 -0
- package/dist/server/handlers/test-utils.d.ts +6 -0
- package/dist/server/handlers/test-utils.d.ts.map +1 -0
- package/dist/server/handlers/test-utils.js +13 -0
- package/dist/server/handlers/test-utils.js.map +1 -0
- package/dist/server/handlers/tools.cjs +11 -11
- package/dist/server/handlers/tools.d.ts +69 -23
- package/dist/server/handlers/tools.d.ts.map +1 -1
- package/dist/server/handlers/tools.js +1 -1
- package/dist/server/handlers/utils.cjs +11 -3
- package/dist/server/handlers/utils.d.ts +5 -0
- package/dist/server/handlers/utils.d.ts.map +1 -1
- package/dist/server/handlers/utils.js +1 -1
- package/dist/server/handlers/vector.cjs +31 -7
- package/dist/server/handlers/vector.d.ts +93 -9
- package/dist/server/handlers/vector.d.ts.map +1 -1
- package/dist/server/handlers/vector.js +1 -1
- package/dist/server/handlers/voice.cjs +21 -9
- package/dist/server/handlers/voice.d.ts +81 -40
- package/dist/server/handlers/voice.d.ts.map +1 -1
- package/dist/server/handlers/voice.js +1 -1
- package/dist/server/handlers/workflows.cjs +37 -37
- package/dist/server/handlers/workflows.d.ts +598 -75
- package/dist/server/handlers/workflows.d.ts.map +1 -1
- package/dist/server/handlers/workflows.js +1 -1
- package/dist/server/handlers.cjs +22 -22
- package/dist/server/handlers.js +11 -11
- package/dist/server/schemas/a2a.d.ts +786 -0
- package/dist/server/schemas/a2a.d.ts.map +1 -0
- package/dist/server/schemas/agent-builder.d.ts +195 -0
- package/dist/server/schemas/agent-builder.d.ts.map +1 -0
- package/dist/server/schemas/agents.d.ts +1375 -0
- package/dist/server/schemas/agents.d.ts.map +1 -0
- package/dist/server/schemas/common.d.ts +165 -0
- package/dist/server/schemas/common.d.ts.map +1 -0
- package/dist/server/schemas/logs.d.ts +124 -0
- package/dist/server/schemas/logs.d.ts.map +1 -0
- package/dist/server/schemas/memory.d.ts +998 -0
- package/dist/server/schemas/memory.d.ts.map +1 -0
- package/dist/server/schemas/observability.d.ts +402 -0
- package/dist/server/schemas/observability.d.ts.map +1 -0
- package/dist/server/schemas/scores.d.ts +259 -0
- package/dist/server/schemas/scores.d.ts.map +1 -0
- package/dist/server/schemas/vectors.d.ts +107 -0
- package/dist/server/schemas/vectors.d.ts.map +1 -0
- package/dist/server/schemas/workflows.d.ts +505 -0
- package/dist/server/schemas/workflows.d.ts.map +1 -0
- package/dist/server/server-adapter/index.cjs +323 -0
- package/dist/server/server-adapter/index.cjs.map +1 -0
- package/dist/server/server-adapter/index.d.ts +52 -0
- package/dist/server/server-adapter/index.d.ts.map +1 -0
- package/dist/server/server-adapter/index.js +309 -0
- package/dist/server/server-adapter/index.js.map +1 -0
- package/dist/server/server-adapter/openapi-utils.d.ts +59 -0
- package/dist/server/server-adapter/openapi-utils.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/a2a.d.ts +3 -0
- package/dist/server/server-adapter/routes/a2a.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/agent-builder.d.ts +3 -0
- package/dist/server/server-adapter/routes/agent-builder.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/agents.d.ts +3 -0
- package/dist/server/server-adapter/routes/agents.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/index.d.ts +41 -0
- package/dist/server/server-adapter/routes/index.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/legacy.d.ts +7 -0
- package/dist/server/server-adapter/routes/legacy.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/logs.d.ts +3 -0
- package/dist/server/server-adapter/routes/logs.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/memory.d.ts +3 -0
- package/dist/server/server-adapter/routes/memory.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/observability.d.ts +3 -0
- package/dist/server/server-adapter/routes/observability.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/route-builder.d.ts +52 -0
- package/dist/server/server-adapter/routes/route-builder.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/scorers.d.ts +3 -0
- package/dist/server/server-adapter/routes/scorers.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/stream-types.d.ts +10 -0
- package/dist/server/server-adapter/routes/stream-types.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/tools.d.ts +3 -0
- package/dist/server/server-adapter/routes/tools.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/vectors.d.ts +3 -0
- package/dist/server/server-adapter/routes/vectors.d.ts.map +1 -0
- package/dist/server/server-adapter/routes/workflows.d.ts +3 -0
- package/dist/server/server-adapter/routes/workflows.d.ts.map +1 -0
- package/dist/server/utils.d.ts +2 -1
- package/dist/server/utils.d.ts.map +1 -1
- package/package.json +24 -9
- package/dist/chunk-46Z2KDQL.js +0 -124
- package/dist/chunk-46Z2KDQL.js.map +0 -1
- package/dist/chunk-73PAWDM5.js +0 -83
- package/dist/chunk-73PAWDM5.js.map +0 -1
- package/dist/chunk-A5SOZY5R.js +0 -502
- package/dist/chunk-A5SOZY5R.js.map +0 -1
- package/dist/chunk-ALOLTNSO.js.map +0 -1
- package/dist/chunk-B6NK4KI5.cjs +0 -128
- package/dist/chunk-B6NK4KI5.cjs.map +0 -1
- package/dist/chunk-BANGX6SC.cjs +0 -200
- package/dist/chunk-BANGX6SC.cjs.map +0 -1
- package/dist/chunk-BHQH5QXD.cjs +0 -172
- package/dist/chunk-BHQH5QXD.cjs.map +0 -1
- package/dist/chunk-BTWIR2B7.cjs +0 -28
- package/dist/chunk-BTWIR2B7.cjs.map +0 -1
- package/dist/chunk-DNUO33HF.js.map +0 -1
- package/dist/chunk-GTZOYEAU.cjs +0 -130
- package/dist/chunk-GTZOYEAU.cjs.map +0 -1
- package/dist/chunk-IGOWG5V5.js +0 -192
- package/dist/chunk-IGOWG5V5.js.map +0 -1
- package/dist/chunk-JO2AZFJN.js +0 -165
- package/dist/chunk-JO2AZFJN.js.map +0 -1
- package/dist/chunk-JZ65BJ6H.cjs +0 -678
- package/dist/chunk-JZ65BJ6H.cjs.map +0 -1
- package/dist/chunk-KWH5QBXP.js +0 -123
- package/dist/chunk-KWH5QBXP.js.map +0 -1
- package/dist/chunk-LPCK5MAF.js +0 -122
- package/dist/chunk-LPCK5MAF.js.map +0 -1
- package/dist/chunk-LWLSQ2W4.cjs.map +0 -1
- package/dist/chunk-M6KNPIZZ.cjs.map +0 -1
- package/dist/chunk-PPMIB3FQ.cjs +0 -88
- package/dist/chunk-PPMIB3FQ.cjs.map +0 -1
- package/dist/chunk-QXWWLCTQ.js.map +0 -1
- package/dist/chunk-S54HNARD.cjs +0 -131
- package/dist/chunk-S54HNARD.cjs.map +0 -1
- package/dist/chunk-SIPNICB3.cjs +0 -517
- package/dist/chunk-SIPNICB3.cjs.map +0 -1
- package/dist/chunk-SRAPUMPM.cjs +0 -620
- package/dist/chunk-SRAPUMPM.cjs.map +0 -1
- package/dist/chunk-SZIFSF4T.js +0 -25
- package/dist/chunk-SZIFSF4T.js.map +0 -1
- package/dist/chunk-TWHS6DKL.js +0 -600
- package/dist/chunk-TWHS6DKL.js.map +0 -1
- package/dist/chunk-VYR3SAFM.js +0 -658
- package/dist/chunk-VYR3SAFM.js.map +0 -1
- package/dist/chunk-XXGID4PQ.cjs.map +0 -1
package/dist/chunk-A5SOZY5R.js
DELETED
|
@@ -1,502 +0,0 @@
|
|
|
1
|
-
import { validateBody } from './chunk-SZIFSF4T.js';
|
|
2
|
-
import { handleError } from './chunk-UXGQZUYZ.js';
|
|
3
|
-
import { HTTPException } from './chunk-6QWQZI4Q.js';
|
|
4
|
-
import { __export } from './chunk-PR4QN5HX.js';
|
|
5
|
-
import { RequestContext } from '@mastra/core/di';
|
|
6
|
-
import { generateEmptyFromSchema } from '@mastra/core/utils';
|
|
7
|
-
|
|
8
|
-
// src/server/handlers/memory.ts
|
|
9
|
-
var memory_exports = {};
|
|
10
|
-
__export(memory_exports, {
|
|
11
|
-
createThreadHandler: () => createThreadHandler,
|
|
12
|
-
deleteMessagesHandler: () => deleteMessagesHandler,
|
|
13
|
-
deleteThreadHandler: () => deleteThreadHandler,
|
|
14
|
-
getMemoryConfigHandler: () => getMemoryConfigHandler,
|
|
15
|
-
getMemoryStatusHandler: () => getMemoryStatusHandler,
|
|
16
|
-
getThreadByIdHandler: () => getThreadByIdHandler,
|
|
17
|
-
getWorkingMemoryHandler: () => getWorkingMemoryHandler,
|
|
18
|
-
listMessagesHandler: () => listMessagesHandler,
|
|
19
|
-
listThreadsHandler: () => listThreadsHandler,
|
|
20
|
-
saveMessagesHandler: () => saveMessagesHandler,
|
|
21
|
-
searchMemoryHandler: () => searchMemoryHandler,
|
|
22
|
-
updateThreadHandler: () => updateThreadHandler,
|
|
23
|
-
updateWorkingMemoryHandler: () => updateWorkingMemoryHandler
|
|
24
|
-
});
|
|
25
|
-
async function getMemoryFromContext({
|
|
26
|
-
mastra,
|
|
27
|
-
agentId,
|
|
28
|
-
requestContext
|
|
29
|
-
}) {
|
|
30
|
-
const logger = mastra.getLogger();
|
|
31
|
-
let agent;
|
|
32
|
-
if (agentId) {
|
|
33
|
-
try {
|
|
34
|
-
agent = mastra.getAgent(agentId);
|
|
35
|
-
} catch (error) {
|
|
36
|
-
logger.debug("Error getting agent from mastra, searching agents for agent", error);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
if (agentId && !agent) {
|
|
40
|
-
logger.debug("Agent not found, searching agents for agent", { agentId });
|
|
41
|
-
const agents = mastra.listAgents();
|
|
42
|
-
if (Object.keys(agents || {}).length) {
|
|
43
|
-
for (const [_, ag] of Object.entries(agents)) {
|
|
44
|
-
try {
|
|
45
|
-
const agents2 = await ag.listAgents();
|
|
46
|
-
if (agents2[agentId]) {
|
|
47
|
-
agent = agents2[agentId];
|
|
48
|
-
break;
|
|
49
|
-
}
|
|
50
|
-
} catch (error) {
|
|
51
|
-
logger.debug("Error getting agent from agent", error);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
if (!agent) {
|
|
56
|
-
throw new HTTPException(404, { message: "Agent not found" });
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (agent) {
|
|
60
|
-
return await agent?.getMemory({
|
|
61
|
-
requestContext: requestContext ?? new RequestContext()
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
async function getMemoryStatusHandler({
|
|
66
|
-
mastra,
|
|
67
|
-
agentId,
|
|
68
|
-
requestContext
|
|
69
|
-
}) {
|
|
70
|
-
try {
|
|
71
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
72
|
-
if (!memory) {
|
|
73
|
-
return { result: false };
|
|
74
|
-
}
|
|
75
|
-
return { result: true };
|
|
76
|
-
} catch (error) {
|
|
77
|
-
return handleError(error, "Error getting memory status");
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
async function getMemoryConfigHandler({
|
|
81
|
-
mastra,
|
|
82
|
-
agentId,
|
|
83
|
-
requestContext
|
|
84
|
-
}) {
|
|
85
|
-
try {
|
|
86
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
87
|
-
if (!memory) {
|
|
88
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
89
|
-
}
|
|
90
|
-
const config = memory.getMergedThreadConfig({});
|
|
91
|
-
return { config };
|
|
92
|
-
} catch (error) {
|
|
93
|
-
return handleError(error, "Error getting memory configuration");
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
async function listThreadsHandler({
|
|
97
|
-
mastra,
|
|
98
|
-
agentId,
|
|
99
|
-
resourceId,
|
|
100
|
-
requestContext,
|
|
101
|
-
page,
|
|
102
|
-
perPage,
|
|
103
|
-
orderBy
|
|
104
|
-
}) {
|
|
105
|
-
try {
|
|
106
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
107
|
-
if (!memory) {
|
|
108
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
109
|
-
}
|
|
110
|
-
validateBody({ resourceId });
|
|
111
|
-
const result = await memory.listThreadsByResourceId({
|
|
112
|
-
resourceId,
|
|
113
|
-
page,
|
|
114
|
-
perPage,
|
|
115
|
-
orderBy
|
|
116
|
-
});
|
|
117
|
-
return result;
|
|
118
|
-
} catch (error) {
|
|
119
|
-
return handleError(error, "Error listing threads");
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
async function getThreadByIdHandler({
|
|
123
|
-
mastra,
|
|
124
|
-
agentId,
|
|
125
|
-
threadId,
|
|
126
|
-
requestContext
|
|
127
|
-
}) {
|
|
128
|
-
try {
|
|
129
|
-
validateBody({ threadId });
|
|
130
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
131
|
-
if (!memory) {
|
|
132
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
133
|
-
}
|
|
134
|
-
const thread = await memory.getThreadById({ threadId });
|
|
135
|
-
if (!thread) {
|
|
136
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
137
|
-
}
|
|
138
|
-
return thread;
|
|
139
|
-
} catch (error) {
|
|
140
|
-
return handleError(error, "Error getting thread");
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
async function saveMessagesHandler({
|
|
144
|
-
mastra,
|
|
145
|
-
agentId,
|
|
146
|
-
body,
|
|
147
|
-
requestContext
|
|
148
|
-
}) {
|
|
149
|
-
try {
|
|
150
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
151
|
-
if (!memory) {
|
|
152
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
153
|
-
}
|
|
154
|
-
if (!body?.messages) {
|
|
155
|
-
throw new HTTPException(400, { message: "Messages are required" });
|
|
156
|
-
}
|
|
157
|
-
if (!Array.isArray(body.messages)) {
|
|
158
|
-
throw new HTTPException(400, { message: "Messages should be an array" });
|
|
159
|
-
}
|
|
160
|
-
const invalidMessages = body.messages.filter((message) => !message.threadId || !message.resourceId);
|
|
161
|
-
if (invalidMessages.length > 0) {
|
|
162
|
-
throw new HTTPException(400, {
|
|
163
|
-
message: `All messages must have threadId and resourceId fields. Found ${invalidMessages.length} invalid message(s).`
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
const processedMessages = body.messages.map((message) => ({
|
|
167
|
-
...message,
|
|
168
|
-
id: message.id || memory.generateId(),
|
|
169
|
-
createdAt: message.createdAt ? new Date(message.createdAt) : /* @__PURE__ */ new Date()
|
|
170
|
-
}));
|
|
171
|
-
const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
|
|
172
|
-
return result;
|
|
173
|
-
} catch (error) {
|
|
174
|
-
return handleError(error, "Error saving messages");
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
async function createThreadHandler({
|
|
178
|
-
mastra,
|
|
179
|
-
agentId,
|
|
180
|
-
body,
|
|
181
|
-
requestContext
|
|
182
|
-
}) {
|
|
183
|
-
try {
|
|
184
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
185
|
-
if (!memory) {
|
|
186
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
187
|
-
}
|
|
188
|
-
validateBody({ resourceId: body?.resourceId });
|
|
189
|
-
const result = await memory.createThread({
|
|
190
|
-
resourceId: body?.resourceId,
|
|
191
|
-
title: body?.title,
|
|
192
|
-
metadata: body?.metadata,
|
|
193
|
-
threadId: body?.threadId
|
|
194
|
-
});
|
|
195
|
-
return result;
|
|
196
|
-
} catch (error) {
|
|
197
|
-
return handleError(error, "Error saving thread to memory");
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
async function updateThreadHandler({
|
|
201
|
-
mastra,
|
|
202
|
-
agentId,
|
|
203
|
-
threadId,
|
|
204
|
-
body,
|
|
205
|
-
requestContext
|
|
206
|
-
}) {
|
|
207
|
-
try {
|
|
208
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
209
|
-
if (!body) {
|
|
210
|
-
throw new HTTPException(400, { message: "Body is required" });
|
|
211
|
-
}
|
|
212
|
-
const { title, metadata, resourceId } = body;
|
|
213
|
-
const updatedAt = /* @__PURE__ */ new Date();
|
|
214
|
-
validateBody({ threadId });
|
|
215
|
-
if (!memory) {
|
|
216
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
217
|
-
}
|
|
218
|
-
const thread = await memory.getThreadById({ threadId });
|
|
219
|
-
if (!thread) {
|
|
220
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
221
|
-
}
|
|
222
|
-
const updatedThread = {
|
|
223
|
-
...thread,
|
|
224
|
-
title: title || thread.title,
|
|
225
|
-
metadata: metadata || thread.metadata,
|
|
226
|
-
resourceId: resourceId || thread.resourceId,
|
|
227
|
-
createdAt: thread.createdAt,
|
|
228
|
-
updatedAt
|
|
229
|
-
};
|
|
230
|
-
const result = await memory.saveThread({ thread: updatedThread });
|
|
231
|
-
return result;
|
|
232
|
-
} catch (error) {
|
|
233
|
-
return handleError(error, "Error updating thread");
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
async function deleteThreadHandler({
|
|
237
|
-
mastra,
|
|
238
|
-
agentId,
|
|
239
|
-
threadId,
|
|
240
|
-
requestContext
|
|
241
|
-
}) {
|
|
242
|
-
try {
|
|
243
|
-
validateBody({ threadId });
|
|
244
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
245
|
-
if (!memory) {
|
|
246
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
247
|
-
}
|
|
248
|
-
const thread = await memory.getThreadById({ threadId });
|
|
249
|
-
if (!thread) {
|
|
250
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
251
|
-
}
|
|
252
|
-
await memory.deleteThread(threadId);
|
|
253
|
-
return { result: "Thread deleted" };
|
|
254
|
-
} catch (error) {
|
|
255
|
-
return handleError(error, "Error deleting thread");
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
async function listMessagesHandler({
|
|
259
|
-
mastra,
|
|
260
|
-
agentId,
|
|
261
|
-
threadId,
|
|
262
|
-
resourceId,
|
|
263
|
-
perPage,
|
|
264
|
-
page,
|
|
265
|
-
orderBy,
|
|
266
|
-
include,
|
|
267
|
-
filter,
|
|
268
|
-
requestContext
|
|
269
|
-
}) {
|
|
270
|
-
try {
|
|
271
|
-
validateBody({ threadId });
|
|
272
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
273
|
-
if (!memory) {
|
|
274
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
275
|
-
}
|
|
276
|
-
if (!threadId) {
|
|
277
|
-
throw new HTTPException(400, { message: "No threadId found" });
|
|
278
|
-
}
|
|
279
|
-
const thread = await memory.getThreadById({ threadId });
|
|
280
|
-
if (!thread) {
|
|
281
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
282
|
-
}
|
|
283
|
-
const result = await memory.recall({
|
|
284
|
-
threadId,
|
|
285
|
-
resourceId,
|
|
286
|
-
perPage,
|
|
287
|
-
page,
|
|
288
|
-
orderBy,
|
|
289
|
-
include,
|
|
290
|
-
filter
|
|
291
|
-
});
|
|
292
|
-
return result;
|
|
293
|
-
} catch (error) {
|
|
294
|
-
return handleError(error, "Error getting messages");
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
async function getWorkingMemoryHandler({
|
|
298
|
-
mastra,
|
|
299
|
-
agentId,
|
|
300
|
-
threadId,
|
|
301
|
-
resourceId,
|
|
302
|
-
requestContext,
|
|
303
|
-
memoryConfig
|
|
304
|
-
}) {
|
|
305
|
-
try {
|
|
306
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
307
|
-
validateBody({ threadId });
|
|
308
|
-
if (!memory) {
|
|
309
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
310
|
-
}
|
|
311
|
-
const thread = await memory.getThreadById({ threadId });
|
|
312
|
-
const threadExists = !!thread;
|
|
313
|
-
const template = await memory.getWorkingMemoryTemplate({ memoryConfig });
|
|
314
|
-
const workingMemoryTemplate = template?.format === "json" ? { ...template, content: JSON.stringify(generateEmptyFromSchema(template.content)) } : template;
|
|
315
|
-
const workingMemory = await memory.getWorkingMemory({ threadId, resourceId, memoryConfig });
|
|
316
|
-
const config = memory.getMergedThreadConfig(memoryConfig || {});
|
|
317
|
-
const source = config.workingMemory?.scope !== "thread" && resourceId ? "resource" : "thread";
|
|
318
|
-
return { workingMemory, source, workingMemoryTemplate, threadExists };
|
|
319
|
-
} catch (error) {
|
|
320
|
-
return handleError(error, "Error getting working memory");
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
async function updateWorkingMemoryHandler({
|
|
324
|
-
mastra,
|
|
325
|
-
agentId,
|
|
326
|
-
threadId,
|
|
327
|
-
body,
|
|
328
|
-
requestContext
|
|
329
|
-
}) {
|
|
330
|
-
try {
|
|
331
|
-
validateBody({ threadId });
|
|
332
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
333
|
-
const { resourceId, memoryConfig, workingMemory } = body;
|
|
334
|
-
if (!memory) {
|
|
335
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
336
|
-
}
|
|
337
|
-
const thread = await memory.getThreadById({ threadId });
|
|
338
|
-
if (!thread) {
|
|
339
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
340
|
-
}
|
|
341
|
-
await memory.updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig });
|
|
342
|
-
return { success: true };
|
|
343
|
-
} catch (error) {
|
|
344
|
-
return handleError(error, "Error updating working memory");
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
async function deleteMessagesHandler({
|
|
348
|
-
mastra,
|
|
349
|
-
agentId,
|
|
350
|
-
messageIds,
|
|
351
|
-
requestContext
|
|
352
|
-
}) {
|
|
353
|
-
try {
|
|
354
|
-
if (messageIds === void 0 || messageIds === null) {
|
|
355
|
-
throw new HTTPException(400, { message: "messageIds is required" });
|
|
356
|
-
}
|
|
357
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
358
|
-
if (!memory) {
|
|
359
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
360
|
-
}
|
|
361
|
-
await memory.deleteMessages(messageIds);
|
|
362
|
-
let count = 1;
|
|
363
|
-
if (Array.isArray(messageIds)) {
|
|
364
|
-
count = messageIds.length;
|
|
365
|
-
}
|
|
366
|
-
return { success: true, message: `${count} message${count === 1 ? "" : "s"} deleted successfully` };
|
|
367
|
-
} catch (error) {
|
|
368
|
-
return handleError(error, "Error deleting messages");
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
async function searchMemoryHandler({
|
|
372
|
-
mastra,
|
|
373
|
-
agentId,
|
|
374
|
-
searchQuery,
|
|
375
|
-
resourceId,
|
|
376
|
-
threadId,
|
|
377
|
-
limit = 20,
|
|
378
|
-
requestContext,
|
|
379
|
-
memoryConfig
|
|
380
|
-
}) {
|
|
381
|
-
try {
|
|
382
|
-
validateBody({ searchQuery, resourceId });
|
|
383
|
-
const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
|
|
384
|
-
if (!memory) {
|
|
385
|
-
throw new HTTPException(400, { message: "Memory is not initialized" });
|
|
386
|
-
}
|
|
387
|
-
const config = memory.getMergedThreadConfig(memoryConfig || {});
|
|
388
|
-
const hasSemanticRecall = !!config?.semanticRecall;
|
|
389
|
-
const resourceScope = typeof config?.semanticRecall === "object" ? config?.semanticRecall?.scope !== "thread" : true;
|
|
390
|
-
if (threadId && !resourceScope) {
|
|
391
|
-
const thread = await memory.getThreadById({ threadId });
|
|
392
|
-
if (!thread) {
|
|
393
|
-
throw new HTTPException(404, { message: "Thread not found" });
|
|
394
|
-
}
|
|
395
|
-
if (thread.resourceId !== resourceId) {
|
|
396
|
-
throw new HTTPException(403, { message: "Thread does not belong to the specified resource" });
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
const searchResults = [];
|
|
400
|
-
if (threadId && !resourceScope) {
|
|
401
|
-
const thread = await memory.getThreadById({ threadId });
|
|
402
|
-
if (!thread) {
|
|
403
|
-
return {
|
|
404
|
-
results: [],
|
|
405
|
-
count: 0,
|
|
406
|
-
query: searchQuery,
|
|
407
|
-
searchScope: resourceScope ? "resource" : "thread",
|
|
408
|
-
searchType: hasSemanticRecall ? "semantic" : "text"
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
if (!threadId) {
|
|
413
|
-
const { threads } = await memory.listThreadsByResourceId({
|
|
414
|
-
resourceId,
|
|
415
|
-
page: 0,
|
|
416
|
-
perPage: 1,
|
|
417
|
-
orderBy: { field: "updatedAt", direction: "DESC" }
|
|
418
|
-
});
|
|
419
|
-
if (threads.length === 0) {
|
|
420
|
-
return {
|
|
421
|
-
results: [],
|
|
422
|
-
count: 0,
|
|
423
|
-
query: searchQuery,
|
|
424
|
-
searchScope: resourceScope ? "resource" : "thread",
|
|
425
|
-
searchType: hasSemanticRecall ? "semantic" : "text"
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
threadId = threads[0].id;
|
|
429
|
-
}
|
|
430
|
-
const beforeRange = typeof config.semanticRecall === `boolean` ? 2 : typeof config.semanticRecall?.messageRange === `number` ? config.semanticRecall.messageRange : config.semanticRecall?.messageRange.before || 2;
|
|
431
|
-
const afterRange = typeof config.semanticRecall === `boolean` ? 2 : typeof config.semanticRecall?.messageRange === `number` ? config.semanticRecall.messageRange : config.semanticRecall?.messageRange.after || 2;
|
|
432
|
-
if (resourceScope && config.semanticRecall) {
|
|
433
|
-
config.semanticRecall = typeof config.semanticRecall === `boolean` ? (
|
|
434
|
-
// make message range 0 so we can highlight the matches in search, message range will include other messages, not the matching ones
|
|
435
|
-
// and we add prev/next messages in a special section on each message anyway
|
|
436
|
-
{ messageRange: 0, topK: 2, scope: "resource" }
|
|
437
|
-
) : { ...config.semanticRecall, messageRange: 0 };
|
|
438
|
-
}
|
|
439
|
-
const threadConfig = memory.getMergedThreadConfig(config || {});
|
|
440
|
-
if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {
|
|
441
|
-
return { results: [], count: 0, query: searchQuery };
|
|
442
|
-
}
|
|
443
|
-
const result = await memory.recall({
|
|
444
|
-
threadId,
|
|
445
|
-
resourceId,
|
|
446
|
-
perPage: threadConfig.lastMessages,
|
|
447
|
-
threadConfig: config,
|
|
448
|
-
vectorSearchString: threadConfig.semanticRecall && searchQuery ? searchQuery : void 0
|
|
449
|
-
});
|
|
450
|
-
const threadIds = Array.from(
|
|
451
|
-
new Set(result.messages.map((m) => m.threadId || threadId).filter(Boolean))
|
|
452
|
-
);
|
|
453
|
-
const fetched = await Promise.all(threadIds.map((id) => memory.getThreadById({ threadId: id })));
|
|
454
|
-
const threadMap = new Map(fetched.filter(Boolean).map((t) => [t.id, t]));
|
|
455
|
-
for (const msg of result.messages) {
|
|
456
|
-
const content = typeof msg.content.content === `string` ? msg.content.content : msg.content.parts?.map((p) => p.type === "text" ? p.text : "").join(" ") || "";
|
|
457
|
-
const msgThreadId = msg.threadId || threadId;
|
|
458
|
-
const thread = threadMap.get(msgThreadId);
|
|
459
|
-
const threadMessages = (await memory.recall({ threadId: msgThreadId })).messages;
|
|
460
|
-
const messageIndex = threadMessages.findIndex((m) => m.id === msg.id);
|
|
461
|
-
const searchResult = {
|
|
462
|
-
id: msg.id,
|
|
463
|
-
role: msg.role,
|
|
464
|
-
content,
|
|
465
|
-
createdAt: msg.createdAt,
|
|
466
|
-
threadId: msgThreadId,
|
|
467
|
-
threadTitle: thread?.title || msgThreadId
|
|
468
|
-
};
|
|
469
|
-
if (messageIndex !== -1) {
|
|
470
|
-
searchResult.context = {
|
|
471
|
-
before: threadMessages.slice(Math.max(0, messageIndex - beforeRange), messageIndex).map((m) => ({
|
|
472
|
-
id: m.id,
|
|
473
|
-
role: m.role,
|
|
474
|
-
content: m.content,
|
|
475
|
-
createdAt: m.createdAt || /* @__PURE__ */ new Date()
|
|
476
|
-
})),
|
|
477
|
-
after: threadMessages.slice(messageIndex + 1, messageIndex + afterRange + 1).map((m) => ({
|
|
478
|
-
id: m.id,
|
|
479
|
-
role: m.role,
|
|
480
|
-
content: m.content,
|
|
481
|
-
createdAt: m.createdAt || /* @__PURE__ */ new Date()
|
|
482
|
-
}))
|
|
483
|
-
};
|
|
484
|
-
}
|
|
485
|
-
searchResults.push(searchResult);
|
|
486
|
-
}
|
|
487
|
-
const sortedResults = searchResults.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()).slice(0, limit);
|
|
488
|
-
return {
|
|
489
|
-
results: sortedResults,
|
|
490
|
-
count: sortedResults.length,
|
|
491
|
-
query: searchQuery,
|
|
492
|
-
searchScope: resourceScope ? "resource" : "thread",
|
|
493
|
-
searchType: hasSemanticRecall ? "semantic" : "text"
|
|
494
|
-
};
|
|
495
|
-
} catch (error) {
|
|
496
|
-
return handleError(error, "Error searching memory");
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
export { createThreadHandler, deleteMessagesHandler, deleteThreadHandler, getMemoryConfigHandler, getMemoryStatusHandler, getThreadByIdHandler, getWorkingMemoryHandler, listMessagesHandler, listThreadsHandler, memory_exports, saveMessagesHandler, searchMemoryHandler, updateThreadHandler, updateWorkingMemoryHandler };
|
|
501
|
-
//# sourceMappingURL=chunk-A5SOZY5R.js.map
|
|
502
|
-
//# sourceMappingURL=chunk-A5SOZY5R.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/handlers/memory.ts"],"names":["agents"],"mappings":";;;;;;;;AAAA,IAAA,cAAA,GAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,qBAAA,EAAA,MAAA,qBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,sBAAA,EAAA,MAAA,sBAAA;AAAA,EAAA,sBAAA,EAAA,MAAA,sBAAA;AAAA,EAAA,oBAAA,EAAA,MAAA,oBAAA;AAAA,EAAA,uBAAA,EAAA,MAAA,uBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,0BAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAkBA,eAAe,oBAAA,CAAqB;AAAA,EAClC,MAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA,EAA2G;AACzG,EAAA,MAAM,MAAA,GAAS,OAAO,SAAA,EAAU;AAChC,EAAA,IAAI,KAAA;AAC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DBMessage } from '@mastra/core/agent';\nimport { RequestContext } from '@mastra/core/di';\nimport type { MastraMemory } from '@mastra/core/memory';\nimport type { StorageListMessagesInput, StorageOrderBy } from '@mastra/core/storage';\nimport { generateEmptyFromSchema } from '@mastra/core/utils';\nimport { HTTPException } from '../http-exception';\nimport type { Context } from '../types';\n\nimport { handleError } from './error';\nimport { validateBody } from './utils';\n\ninterface MemoryContext extends Context {\n agentId?: string;\n resourceId?: string;\n threadId?: string;\n requestContext?: RequestContext;\n}\n\nasync function getMemoryFromContext({\n mastra,\n agentId,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'>): Promise<MastraMemory | null | undefined> {\n const logger = mastra.getLogger();\n let agent;\n if (agentId) {\n try {\n agent = mastra.getAgent(agentId);\n } catch (error) {\n logger.debug('Error getting agent from mastra, searching agents for agent', error);\n }\n }\n if (agentId && !agent) {\n logger.debug('Agent not found, searching agents for agent', { agentId });\n const agents = mastra.listAgents();\n if (Object.keys(agents || {}).length) {\n for (const [_, ag] of Object.entries(agents)) {\n try {\n const agents = await ag.listAgents();\n\n if (agents[agentId]) {\n agent = agents[agentId];\n break;\n }\n } catch (error) {\n logger.debug('Error getting agent from agent', error);\n }\n }\n }\n\n if (!agent) {\n throw new HTTPException(404, { message: 'Agent not found' });\n }\n }\n\n if (agent) {\n return await agent?.getMemory({\n requestContext: requestContext ?? new RequestContext(),\n });\n }\n}\n\n// Memory handlers\nexport async function getMemoryStatusHandler({\n mastra,\n agentId,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'>) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n return { result: false };\n }\n\n return { result: true };\n } catch (error) {\n return handleError(error, 'Error getting memory status');\n }\n}\n\nexport async function getMemoryConfigHandler({\n mastra,\n agentId,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'>) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n // Get the merged configuration (defaults + custom)\n const config = memory.getMergedThreadConfig({});\n\n return { config };\n } catch (error) {\n return handleError(error, 'Error getting memory configuration');\n }\n}\n\nexport async function listThreadsHandler({\n mastra,\n agentId,\n resourceId,\n requestContext,\n page,\n perPage,\n orderBy,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'resourceId' | 'requestContext'> & {\n page: number;\n perPage: number | false;\n orderBy?: StorageOrderBy;\n}) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n validateBody({ resourceId });\n\n const result = await memory.listThreadsByResourceId({\n resourceId: resourceId!,\n page,\n perPage,\n orderBy,\n });\n return result;\n } catch (error) {\n return handleError(error, 'Error listing threads');\n }\n}\n\nexport async function getThreadByIdHandler({\n mastra,\n agentId,\n threadId,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'>) {\n try {\n validateBody({ threadId });\n\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n const thread = await memory.getThreadById({ threadId: threadId! });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n\n return thread;\n } catch (error) {\n return handleError(error, 'Error getting thread');\n }\n}\n\nexport async function saveMessagesHandler({\n mastra,\n agentId,\n body,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'> & {\n body: {\n messages: Parameters<MastraMemory['saveMessages']>[0]['messages'];\n };\n}) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n if (!body?.messages) {\n throw new HTTPException(400, { message: 'Messages are required' });\n }\n\n if (!Array.isArray(body.messages)) {\n throw new HTTPException(400, { message: 'Messages should be an array' });\n }\n\n // Validate that all messages have threadId and resourceId\n const invalidMessages = body.messages.filter(message => !message.threadId || !message.resourceId);\n if (invalidMessages.length > 0) {\n throw new HTTPException(400, {\n message: `All messages must have threadId and resourceId fields. Found ${invalidMessages.length} invalid message(s).`,\n });\n }\n\n const processedMessages = body.messages.map(message => ({\n ...message,\n id: message.id || memory.generateId(),\n createdAt: message.createdAt ? new Date(message.createdAt) : new Date(),\n }));\n\n const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });\n return result;\n } catch (error) {\n return handleError(error, 'Error saving messages');\n }\n}\n\nexport async function createThreadHandler({\n mastra,\n agentId,\n body,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'> & {\n body?: Omit<Parameters<MastraMemory['createThread']>[0], 'resourceId'> & { resourceId?: string };\n}) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n validateBody({ resourceId: body?.resourceId });\n\n const result = await memory.createThread({\n resourceId: body?.resourceId!,\n title: body?.title,\n metadata: body?.metadata,\n threadId: body?.threadId,\n });\n return result;\n } catch (error) {\n return handleError(error, 'Error saving thread to memory');\n }\n}\n\nexport async function updateThreadHandler({\n mastra,\n agentId,\n threadId,\n body,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'> & {\n body?: Parameters<MastraMemory['saveThread']>[0]['thread'];\n}) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!body) {\n throw new HTTPException(400, { message: 'Body is required' });\n }\n\n const { title, metadata, resourceId } = body;\n const updatedAt = new Date();\n\n validateBody({ threadId });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n const thread = await memory.getThreadById({ threadId: threadId! });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n\n const updatedThread = {\n ...thread,\n title: title || thread.title,\n metadata: metadata || thread.metadata,\n resourceId: resourceId || thread.resourceId,\n createdAt: thread.createdAt,\n updatedAt,\n };\n\n const result = await memory.saveThread({ thread: updatedThread });\n return result;\n } catch (error) {\n return handleError(error, 'Error updating thread');\n }\n}\n\nexport async function deleteThreadHandler({\n mastra,\n agentId,\n threadId,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'>) {\n try {\n validateBody({ threadId });\n\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n const thread = await memory.getThreadById({ threadId: threadId! });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n\n await memory.deleteThread(threadId!);\n return { result: 'Thread deleted' };\n } catch (error) {\n return handleError(error, 'Error deleting thread');\n }\n}\n\nexport async function listMessagesHandler({\n mastra,\n agentId,\n threadId,\n resourceId,\n perPage,\n page,\n orderBy,\n include,\n filter,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'> &\n Omit<StorageListMessagesInput, 'threadId'>) {\n try {\n validateBody({ threadId });\n\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n if (!threadId) {\n throw new HTTPException(400, { message: 'No threadId found' });\n }\n\n const thread = await memory.getThreadById({ threadId: threadId });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n\n const result = await memory.recall({\n threadId: threadId,\n resourceId,\n perPage,\n page,\n orderBy,\n include,\n filter,\n });\n return result;\n } catch (error) {\n return handleError(error, 'Error getting messages');\n }\n}\n\n/**\n * Handler to get the working memory for a thread (optionally resource-scoped).\n * @returns workingMemory - the working memory for the thread\n * @returns source - thread or resource\n */\nexport async function getWorkingMemoryHandler({\n mastra,\n agentId,\n threadId,\n resourceId,\n requestContext,\n memoryConfig,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'> & {\n resourceId?: Parameters<MastraMemory['getWorkingMemory']>[0]['resourceId'];\n memoryConfig?: Parameters<MastraMemory['getWorkingMemory']>[0]['memoryConfig'];\n}) {\n try {\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n validateBody({ threadId });\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n const thread = await memory.getThreadById({ threadId: threadId! });\n const threadExists = !!thread;\n const template = await memory.getWorkingMemoryTemplate({ memoryConfig });\n const workingMemoryTemplate =\n template?.format === 'json'\n ? { ...template, content: JSON.stringify(generateEmptyFromSchema(template.content)) }\n : template;\n const workingMemory = await memory.getWorkingMemory({ threadId: threadId!, resourceId, memoryConfig });\n const config = memory.getMergedThreadConfig(memoryConfig || {});\n const source = config.workingMemory?.scope !== 'thread' && resourceId ? 'resource' : 'thread';\n return { workingMemory, source, workingMemoryTemplate, threadExists };\n } catch (error) {\n return handleError(error, 'Error getting working memory');\n }\n}\n\n/**\n * Handler to update the working memory for a thread (optionally resource-scoped).\n * @param threadId - the thread id\n * @param body - the body containing the working memory to update and the resource id (optional)\n */\nexport async function updateWorkingMemoryHandler({\n mastra,\n agentId,\n threadId,\n body,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'threadId' | 'requestContext'> & {\n body: Omit<Parameters<MastraMemory['updateWorkingMemory']>[0], 'threadId'>;\n}) {\n try {\n validateBody({ threadId });\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n const { resourceId, memoryConfig, workingMemory } = body;\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n const thread = await memory.getThreadById({ threadId: threadId! });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n\n await memory.updateWorkingMemory({ threadId: threadId!, resourceId, workingMemory, memoryConfig });\n return { success: true };\n } catch (error) {\n return handleError(error, 'Error updating working memory');\n }\n}\n\ninterface SearchResult {\n id: string;\n role: string;\n content: any;\n createdAt: Date;\n threadId?: string;\n threadTitle?: string;\n score?: number;\n context?: {\n before?: SearchResult[];\n after?: SearchResult[];\n };\n}\n\ninterface SearchResponse {\n results: SearchResult[];\n count: number;\n query: string;\n searchScope?: string;\n searchType?: string;\n}\n\n/**\n * Handler to delete one or more messages.\n * @param messageIds - Can be a single ID, array of IDs, or objects with ID property\n */\nexport async function deleteMessagesHandler({\n mastra,\n agentId,\n messageIds,\n requestContext,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'> & {\n messageIds: string | string[] | { id: string } | { id: string }[];\n}) {\n try {\n if (messageIds === undefined || messageIds === null) {\n throw new HTTPException(400, { message: 'messageIds is required' });\n }\n\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n // Delete the messages - let the memory method handle validation\n await memory.deleteMessages(messageIds as any);\n\n // Count messages for response\n let count = 1;\n if (Array.isArray(messageIds)) {\n count = messageIds.length;\n }\n\n return { success: true, message: `${count} message${count === 1 ? '' : 's'} deleted successfully` };\n } catch (error) {\n return handleError(error, 'Error deleting messages');\n }\n}\n\nexport async function searchMemoryHandler({\n mastra,\n agentId,\n searchQuery,\n resourceId,\n threadId,\n limit = 20,\n requestContext,\n memoryConfig,\n}: Pick<MemoryContext, 'mastra' | 'agentId' | 'requestContext'> & {\n searchQuery: string;\n resourceId: string;\n threadId?: string;\n limit?: number;\n memoryConfig?: any;\n}): Promise<SearchResponse | ReturnType<typeof handleError>> {\n try {\n validateBody({ searchQuery, resourceId });\n\n const memory = await getMemoryFromContext({ mastra, agentId, requestContext });\n if (!memory) {\n throw new HTTPException(400, { message: 'Memory is not initialized' });\n }\n\n // Get memory configuration first to check scope\n const config = memory.getMergedThreadConfig(memoryConfig || {});\n const hasSemanticRecall = !!config?.semanticRecall;\n const resourceScope =\n typeof config?.semanticRecall === 'object' ? config?.semanticRecall?.scope !== 'thread' : true;\n\n // Only validate thread ownership if we're in thread scope\n if (threadId && !resourceScope) {\n const thread = await memory.getThreadById({ threadId });\n if (!thread) {\n throw new HTTPException(404, { message: 'Thread not found' });\n }\n if (thread.resourceId !== resourceId) {\n throw new HTTPException(403, { message: 'Thread does not belong to the specified resource' });\n }\n }\n\n const searchResults: SearchResult[] = [];\n\n // If threadId is provided and scope is thread-based, check if the thread exists\n if (threadId && !resourceScope) {\n const thread = await memory.getThreadById({ threadId });\n if (!thread) {\n // Thread doesn't exist yet (new unsaved thread) - return empty results\n return {\n results: [],\n count: 0,\n query: searchQuery,\n searchScope: resourceScope ? 'resource' : 'thread',\n searchType: hasSemanticRecall ? 'semantic' : 'text',\n };\n }\n }\n\n // If no threadId provided, get one from the resource\n if (!threadId) {\n const { threads } = await memory.listThreadsByResourceId({\n resourceId,\n page: 0,\n perPage: 1,\n orderBy: { field: 'updatedAt', direction: 'DESC' },\n });\n\n if (threads.length === 0) {\n return {\n results: [],\n count: 0,\n query: searchQuery,\n searchScope: resourceScope ? 'resource' : 'thread',\n searchType: hasSemanticRecall ? 'semantic' : 'text',\n };\n }\n\n // Use first thread - Memory class will handle scope internally\n threadId = threads[0]!.id;\n }\n\n const beforeRange =\n typeof config.semanticRecall === `boolean`\n ? 2\n : typeof config.semanticRecall?.messageRange === `number`\n ? config.semanticRecall.messageRange\n : config.semanticRecall?.messageRange.before || 2;\n const afterRange =\n typeof config.semanticRecall === `boolean`\n ? 2\n : typeof config.semanticRecall?.messageRange === `number`\n ? config.semanticRecall.messageRange\n : config.semanticRecall?.messageRange.after || 2;\n\n if (resourceScope && config.semanticRecall) {\n config.semanticRecall =\n typeof config.semanticRecall === `boolean`\n ? // make message range 0 so we can highlight the matches in search, message range will include other messages, not the matching ones\n // and we add prev/next messages in a special section on each message anyway\n { messageRange: 0, topK: 2, scope: 'resource' }\n : { ...config.semanticRecall, messageRange: 0 };\n }\n\n // Single call to recall - just like the agent does\n // The Memory class handles scope (thread vs resource) internally\n const threadConfig = memory.getMergedThreadConfig(config || {});\n if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {\n return { results: [], count: 0, query: searchQuery };\n }\n\n const result = await memory.recall({\n threadId,\n resourceId,\n perPage: threadConfig.lastMessages,\n threadConfig: config,\n vectorSearchString: threadConfig.semanticRecall && searchQuery ? searchQuery : undefined,\n });\n\n // Get all threads to build context and show which thread each message is from\n // Fetch threads by IDs from the actual messages to avoid truncation\n const threadIds = Array.from(\n new Set(result.messages.map((m: MastraDBMessage) => m.threadId || threadId!).filter(Boolean)),\n );\n const fetched = await Promise.all(threadIds.map((id: string) => memory.getThreadById({ threadId: id })));\n const threadMap = new Map(fetched.filter(Boolean).map(t => [t!.id, t!]));\n\n // Process each message in the results\n for (const msg of result.messages) {\n const content =\n typeof msg.content.content === `string`\n ? msg.content.content\n : msg.content.parts?.map((p: any) => (p.type === 'text' ? p.text : '')).join(' ') || '';\n\n const msgThreadId = msg.threadId || threadId;\n const thread = threadMap.get(msgThreadId);\n\n // Get thread messages for context\n const threadMessages = (await memory.recall({ threadId: msgThreadId })).messages;\n const messageIndex = threadMessages.findIndex(m => m.id === msg.id);\n\n const searchResult: SearchResult = {\n id: msg.id,\n role: msg.role,\n content,\n createdAt: msg.createdAt,\n threadId: msgThreadId,\n threadTitle: thread?.title || msgThreadId,\n };\n\n if (messageIndex !== -1) {\n searchResult.context = {\n before: threadMessages.slice(Math.max(0, messageIndex - beforeRange), messageIndex).map(m => ({\n id: m.id,\n role: m.role,\n content: m.content,\n createdAt: m.createdAt || new Date(),\n })),\n after: threadMessages.slice(messageIndex + 1, messageIndex + afterRange + 1).map(m => ({\n id: m.id,\n role: m.role,\n content: m.content,\n createdAt: m.createdAt || new Date(),\n })),\n };\n }\n\n searchResults.push(searchResult);\n }\n\n // Sort by date (newest first) and limit\n const sortedResults = searchResults\n .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())\n .slice(0, limit);\n\n return {\n results: sortedResults,\n count: sortedResults.length,\n query: searchQuery,\n searchScope: resourceScope ? 'resource' : 'thread',\n searchType: hasSemanticRecall ? 'semantic' : 'text',\n };\n } catch (error) {\n return handleError(error, 'Error searching memory');\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/handlers/a2a.ts","../src/server/a2a/protocol.ts","../src/server/a2a/tasks.ts"],"names":["MastraA2AError","result"],"mappings":";;;;;;AAAA,IAAA,WAAA,GAAA;AAAA,QAAA,CAAA,WAAA,EAAA;AAAA,EAAA,uBAAA,EAAA,MAAA,uBAAA;AAAA,EAAA,wBAAA,EAAA,MAAA,wBAAA;AAAA,EAAA,iBAAA,EAAA,MAAA,iBAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,gBAAA,EAAA,MAAA,gBAAA;AAAA,EAAA,aAAA,EAAA,MAAA;AAAA,CAAA,CAAA;ACMO,SAAS,cAAA,CACd,KAAA,EACA,KAAA,EACA,MAAA,EACA,MAAA,EACgC;AAChC,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI,iBAAiB,cAAA,EAAgB;AACnC,IAAA,QAAA,GAAW,KAAA;AAAA,EACb,CAAA,MAAA,IAAW,iBAAiB,KAAA,EAAO;AAEjC,IAAA,QAAA,GAAW,cAAA,CAAe,cAAc,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,KAAA,CAAM,OAAO,CAAA;AAAA,EAC/E,CAAA,MAAO;AAEL,IAAA,QAAA,GAAW,cAAA,CAAe,aAAA,CAAc,4BAAA,EAA8B,KAAK,CAAA;AAAA,EAC7E;AAGA,EAAA,IAAI,MAAA,IAAU,CAAC,QAAA,CAAS,MAAA,EAAQ;AAC9B,IAAA,QAAA,CAAS,MAAA,GAAS,MAAA;AAAA,EACpB;AAEA,EAAA,MAAA,EAAQ,KAAA,CAAM,mCAAmC,QAAA,CAAS,MAAA,IAAU,KAAK,CAAA,SAAA,EAAY,KAAA,IAAS,KAAK,CAAA,EAAA,CAAA,EAAM,Q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ACD,QAAA,OAAO,MAAA;AAAA,MAET,KAAK,WAAA,EAAa;AAChB,QAAA,MAAMA,OAAAA,GAAS,MAAM,aAAA,CAAc;AAAA,UACjC,SAAA;AAAA,UACA,SAAA;AAAA,UACA,OAAA;AAAA,UACA;AAAA,SACD,CAAA;AAED,QAAA,OAAOA,OAAAA;AAAA,MACT;AAAA,MACA,KAAK,cAAA,EAAgB;AACnB,QAAA,MAAMA,OAAAA,GAAS,MAAM,gBAAA,CAAiB;AAAA,UACpC,SAAA;AAAA,UACA,SAAA;AAAA,UACA,OAAA;AAAA,UACA;AAAA,SACD,CAAA;AAED,QAAA,OAAOA,OAAAA;AAAA,MACT;AAAA,MACA;AACE,QAAA,MAAMD,cAAAA,CAAe,eAAe,MAAM,CAAA;AAAA;AAC9C,EACF,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,KAAA,YAAiBA,cAAAA,IAAkB,MAAA,IAAU,CAAC,MAAM,MAAA,EAAQ;AAC9D,MAAA,KAAA,CAAM,MAAA,GAAS,MAAA;AAAA,IACjB;AAEA,IAAA,OAAO,cAAA,CAAe,KAAA,EAAO,SAAA,EAAW,MAAA,EAAQ,MAAM,CAAA;AAAA,EACxD;AACF","file":"chunk-ALOLTNSO.js","sourcesContent":["import { MastraA2AError } from '@mastra/core/a2a';\nimport type {\n MessageSendParams,\n TaskQueryParams,\n TaskIdParams,\n AgentCard,\n TaskStatus,\n TaskState,\n} from '@mastra/core/a2a';\nimport type { Agent } from '@mastra/core/agent';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { z } from 'zod';\nimport { convertToCoreMessage, normalizeError, createSuccessResponse, createErrorResponse } from '../a2a/protocol';\nimport type { InMemoryTaskStore } from '../a2a/store';\nimport { applyUpdateToTask, createTaskContext, loadOrCreateTask } from '../a2a/tasks';\nimport type { Context } from '../types';\nimport { convertInstructionsToString } from '../utils';\n\nconst messageSendParamsSchema = z.object({\n message: z.object({\n role: z.enum(['user', 'agent']),\n parts: z.array(\n z.object({\n kind: z.enum(['text']),\n text: z.string(),\n }),\n ),\n kind: z.literal('message'),\n messageId: z.string(),\n contextId: z.string().optional(),\n taskId: z.string().optional(),\n referenceTaskIds: z.array(z.string()).optional(),\n extensions: z.array(z.string()).optional(),\n metadata: z.record(z.any()).optional(),\n }),\n});\n\nexport async function getAgentCardByIdHandler({\n mastra,\n agentId,\n executionUrl = `/a2a/${agentId}`,\n provider = {\n organization: 'Mastra',\n url: 'https://mastra.ai',\n },\n version = '1.0',\n requestContext,\n}: Context & {\n requestContext: RequestContext;\n agentId: keyof ReturnType<typeof mastra.listAgents>;\n executionUrl?: string;\n version?: string;\n provider?: {\n organization: string;\n url: string;\n };\n}): Promise<AgentCard> {\n const agent = mastra.getAgent(agentId);\n\n if (!agent) {\n throw new Error(`Agent with ID ${agentId} not found`);\n }\n\n const [instructions, tools] = await Promise.all([\n agent.getInstructions({ requestContext }),\n agent.listTools({ requestContext }),\n ]);\n\n // Extract agent information to create the AgentCard\n const agentCard: AgentCard = {\n name: agent.id || agentId,\n description: convertInstructionsToString(instructions),\n url: executionUrl,\n provider,\n version,\n capabilities: {\n streaming: true, // All agents support streaming\n pushNotifications: false,\n stateTransitionHistory: false,\n },\n defaultInputModes: ['text'],\n defaultOutputModes: ['text'],\n // Convert agent tools to skills format for A2A protocol\n skills: Object.entries(tools).map(([toolId, tool]) => ({\n id: toolId,\n name: toolId,\n description: tool.description || `Tool: ${toolId}`,\n // Optional fields\n tags: ['tool'],\n })),\n };\n\n return agentCard;\n}\n\nfunction validateMessageSendParams(params: MessageSendParams) {\n try {\n messageSendParamsSchema.parse(params);\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw MastraA2AError.invalidParams((error as z.ZodError).errors[0]!.message);\n }\n\n throw error;\n }\n}\n\nexport async function handleMessageSend({\n requestId,\n params,\n taskStore,\n agent,\n agentId,\n logger,\n requestContext,\n}: {\n requestId: string;\n params: MessageSendParams;\n taskStore: InMemoryTaskStore;\n agent: Agent;\n agentId: string;\n logger?: IMastraLogger;\n requestContext: RequestContext;\n}) {\n validateMessageSendParams(params);\n\n const { message, metadata } = params;\n const { contextId } = message;\n const taskId = message.taskId || crypto.randomUUID();\n\n // Load or create task\n let currentData = await loadOrCreateTask({\n taskId,\n taskStore,\n agentId,\n message,\n contextId,\n metadata,\n });\n\n // Use the new TaskContext definition, passing history\n const context = createTaskContext({\n task: currentData,\n userMessage: message,\n history: currentData.history || [],\n activeCancellations: taskStore.activeCancellations,\n });\n\n try {\n const { text } = await agent.generate([convertToCoreMessage(message)], {\n runId: taskId,\n requestContext,\n });\n\n currentData = applyUpdateToTask(currentData, {\n state: 'completed',\n message: {\n messageId: crypto.randomUUID(),\n role: 'agent',\n parts: [\n {\n kind: 'text',\n text: text,\n },\n ],\n kind: 'message',\n },\n });\n\n await taskStore.save({ agentId, data: currentData });\n context.task = currentData;\n } catch (handlerError) {\n // If handler throws, apply 'failed' status, save, and rethrow\n const failureStatusUpdate: Omit<TaskStatus, 'timestamp'> = {\n state: 'failed',\n message: {\n messageId: crypto.randomUUID(),\n role: 'agent',\n parts: [\n {\n kind: 'text',\n text: `Handler failed: ${handlerError instanceof Error ? handlerError.message : String(handlerError)}`,\n },\n ],\n kind: 'message',\n },\n };\n currentData = applyUpdateToTask(currentData, failureStatusUpdate);\n\n try {\n await taskStore.save({ agentId, data: currentData });\n } catch (saveError) {\n // @ts-expect-error saveError is an unknown error\n logger?.error(`Failed to save task ${currentData.id} after handler error:`, saveError?.message);\n }\n\n return normalizeError(handlerError, requestId, currentData.id, logger); // Rethrow original error\n }\n\n // The loop finished, send the final task state\n return createSuccessResponse(requestId, currentData);\n}\n\nexport async function handleTaskGet({\n requestId,\n taskStore,\n agentId,\n taskId,\n}: {\n requestId: string;\n taskStore: InMemoryTaskStore;\n agentId: string;\n taskId: string;\n}) {\n const task = await taskStore.load({ agentId, taskId });\n\n if (!task) {\n throw MastraA2AError.taskNotFound(taskId);\n }\n\n return createSuccessResponse(requestId, task);\n}\n\nexport async function* handleMessageStream({\n requestId,\n params,\n taskStore,\n agent,\n agentId,\n logger,\n requestContext,\n}: {\n requestId: string;\n params: MessageSendParams;\n taskStore: InMemoryTaskStore;\n agent: Agent;\n agentId: string;\n logger?: IMastraLogger;\n requestContext: RequestContext;\n}) {\n yield createSuccessResponse(requestId, {\n state: 'working',\n message: {\n messageId: crypto.randomUUID(),\n kind: 'message',\n role: 'agent',\n parts: [{ kind: 'text', text: 'Generating response...' }],\n },\n });\n\n let result;\n try {\n result = await handleMessageSend({\n requestId,\n params,\n taskStore,\n agent,\n agentId,\n requestContext,\n logger,\n });\n } catch (err) {\n if (!(err instanceof MastraA2AError)) {\n throw err;\n }\n\n result = createErrorResponse(requestId, err.toJSONRPCError());\n }\n\n yield result;\n}\n\nexport async function handleTaskCancel({\n requestId,\n taskStore,\n agentId,\n taskId,\n logger,\n}: {\n requestId: string;\n taskStore: InMemoryTaskStore;\n agentId: string;\n taskId: string;\n logger?: IMastraLogger;\n}) {\n // Load task and history\n let data = await taskStore.load({\n agentId,\n taskId,\n });\n\n if (!data) {\n throw MastraA2AError.taskNotFound(taskId);\n }\n\n // Check if cancelable (not already in a final state)\n const finalStates: TaskState[] = ['completed', 'failed', 'canceled'];\n\n if (finalStates.includes(data.status.state)) {\n logger?.info(`Task ${taskId} already in final state ${data.status.state}, cannot cancel.`);\n return createSuccessResponse(requestId, data);\n }\n\n // Signal cancellation\n taskStore.activeCancellations.add(taskId);\n\n // Apply 'canceled' state update\n const cancelUpdate: Omit<TaskStatus, 'timestamp'> = {\n state: 'canceled',\n message: {\n role: 'agent',\n parts: [{ kind: 'text', text: 'Task cancelled by request.' }],\n kind: 'message',\n messageId: crypto.randomUUID(),\n },\n };\n\n data = applyUpdateToTask(data, cancelUpdate);\n\n // Save the updated state\n await taskStore.save({ agentId, data });\n\n // Remove from active cancellations *after* saving\n taskStore.activeCancellations.delete(taskId);\n\n // Return the updated task object\n return createSuccessResponse(requestId, data);\n}\n\nexport async function getAgentExecutionHandler({\n requestId,\n mastra,\n agentId,\n requestContext,\n method,\n params,\n taskStore,\n logger,\n}: Context & {\n requestId: string;\n requestContext: RequestContext;\n agentId: string;\n method: 'message/send' | 'message/stream' | 'tasks/get' | 'tasks/cancel';\n params: MessageSendParams | TaskQueryParams | TaskIdParams;\n taskStore: InMemoryTaskStore;\n logger?: IMastraLogger;\n}): Promise<any> {\n const agent = mastra.getAgent(agentId);\n\n let taskId: string | undefined; // For error context\n\n try {\n // Attempt to get task ID early for error context. Cast params to any to access id.\n // Proper validation happens within specific handlers.\n taskId = 'id' in params ? params.id : params.message?.taskId || 'No task ID provided';\n\n // 2. Route based on method\n switch (method) {\n case 'message/send': {\n const result = await handleMessageSend({\n requestId,\n params: params as MessageSendParams,\n taskStore,\n agent,\n agentId,\n requestContext,\n });\n return result;\n }\n case 'message/stream':\n const result = await handleMessageStream({\n requestId,\n taskStore,\n params: params as MessageSendParams,\n agent,\n agentId,\n requestContext,\n });\n return result;\n\n case 'tasks/get': {\n const result = await handleTaskGet({\n requestId,\n taskStore,\n agentId,\n taskId,\n });\n\n return result;\n }\n case 'tasks/cancel': {\n const result = await handleTaskCancel({\n requestId,\n taskStore,\n agentId,\n taskId,\n });\n\n return result;\n }\n default:\n throw MastraA2AError.methodNotFound(method);\n }\n } catch (error) {\n if (error instanceof MastraA2AError && taskId && !error.taskId) {\n error.taskId = taskId; // Add task ID context if missing\n }\n\n return normalizeError(error, requestId, taskId, logger);\n }\n}\n","import { MastraA2AError } from '@mastra/core/a2a';\n\nimport type { JSONRPCError, JSONRPCResponse, Message, Part } from '@mastra/core/a2a';\nimport type { CoreMessage } from '@mastra/core/llm';\nimport type { IMastraLogger } from '@mastra/core/logger';\n\nexport function normalizeError(\n error: any,\n reqId: number | string | null,\n taskId?: string,\n logger?: IMastraLogger,\n): JSONRPCResponse<null, unknown> {\n let a2aError: MastraA2AError;\n if (error instanceof MastraA2AError) {\n a2aError = error;\n } else if (error instanceof Error) {\n // Generic JS error\n a2aError = MastraA2AError.internalError(error.message, { stack: error.stack });\n } else {\n // Unknown error type\n a2aError = MastraA2AError.internalError('An unknown error occurred.', error);\n }\n\n // Ensure Task ID context is present if possible\n if (taskId && !a2aError.taskId) {\n a2aError.taskId = taskId;\n }\n\n logger?.error(`Error processing request (Task: ${a2aError.taskId ?? 'N/A'}, ReqID: ${reqId ?? 'N/A'}):`, a2aError);\n\n return createErrorResponse(reqId, a2aError.toJSONRPCError());\n}\n\nexport function createErrorResponse(\n id: number | string | null,\n error: JSONRPCError<unknown>,\n): JSONRPCResponse<null, unknown> {\n // For errors, ID should be the same as request ID, or null if that couldn't be determined\n return {\n jsonrpc: '2.0',\n id: id, // Can be null if request ID was invalid/missing\n error: error,\n };\n}\n\nexport function createSuccessResponse<T>(id: number | string | null, result: T): JSONRPCResponse<T> {\n if (!id) {\n // This shouldn't happen for methods that expect a response, but safeguard\n throw MastraA2AError.internalError('Cannot create success response for null ID.');\n }\n\n return {\n jsonrpc: '2.0',\n id: id,\n result: result,\n };\n}\n\nexport function convertToCoreMessage(message: Message): CoreMessage {\n return {\n role: message.role === 'user' ? 'user' : 'assistant',\n content: message.parts.map(msg => convertToCoreMessagePart(msg)),\n };\n}\n\nfunction convertToCoreMessagePart(part: Part) {\n switch (part.kind) {\n case 'text':\n return {\n type: 'text',\n text: part.text,\n } as const;\n case 'file':\n return {\n type: 'file',\n data: 'uri' in part.file ? new URL(part.file.uri) : part.file.bytes,\n mimeType: part.file.mimeType!,\n } as const;\n case 'data':\n throw new Error('Data parts are not supported in core messages');\n }\n}\n","import type {\n Message,\n Task,\n TaskState,\n TaskStatus,\n TaskContext,\n TaskArtifactUpdateEvent,\n Artifact,\n} from '@mastra/core/a2a';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { InMemoryTaskStore } from './store';\n\nfunction isTaskStatusUpdate(update: TaskStatus | TaskArtifactUpdateEvent): update is Omit<TaskStatus, 'timestamp'> {\n return 'state' in update && !('parts' in update);\n}\n\nfunction isArtifactUpdate(update: TaskStatus | TaskArtifactUpdateEvent): update is TaskArtifactUpdateEvent {\n return 'kind' in update && update.kind === 'artifact-update';\n}\n\nexport function applyUpdateToTask(\n current: Task,\n update: Omit<TaskStatus, 'timestamp'> | TaskArtifactUpdateEvent,\n): Task {\n let newTask = structuredClone(current);\n\n if (isTaskStatusUpdate(update)) {\n // Merge status update\n newTask.status = {\n ...newTask.status, // Keep existing properties if not overwritten\n ...update, // Apply updates\n timestamp: new Date().toISOString(),\n };\n } else if (isArtifactUpdate(update)) {\n // Handle artifact update\n if (!newTask.artifacts) {\n newTask.artifacts = [];\n } else {\n // Ensure we're working with a copy of the artifacts array\n newTask.artifacts = [...newTask.artifacts];\n }\n\n const artifact = update.artifact;\n const existingIndex = newTask.artifacts.findIndex(a => a.name === artifact.name);\n const existingArtifact = newTask.artifacts[existingIndex];\n\n if (existingArtifact) {\n if (update.append) {\n // Create a deep copy for modification to avoid mutating original\n const appendedArtifact = JSON.parse(JSON.stringify(existingArtifact)) as Artifact;\n appendedArtifact.parts.push(...artifact.parts);\n if (artifact.metadata) {\n appendedArtifact.metadata = {\n ...(appendedArtifact.metadata || {}),\n ...artifact.metadata,\n };\n }\n if (artifact.description) appendedArtifact.description = artifact.description;\n newTask.artifacts[existingIndex] = appendedArtifact; // Replace with appended version\n } else {\n // Overwrite artifact at index (with a copy of the update)\n newTask.artifacts[existingIndex] = { ...artifact };\n }\n } else {\n newTask.artifacts.push({ ...artifact });\n }\n }\n\n return newTask;\n}\n\nexport async function loadOrCreateTask({\n agentId,\n taskId,\n taskStore,\n message,\n contextId,\n metadata,\n logger,\n}: {\n agentId: string;\n taskId: string;\n taskStore: InMemoryTaskStore;\n message: Message;\n contextId?: string;\n metadata?: Record<string, unknown>;\n logger?: IMastraLogger;\n}): Promise<Task> {\n const data = await taskStore.load({ agentId, taskId });\n\n // Create new task if none exists\n if (!data) {\n const initialTask: Task = {\n id: taskId,\n contextId: contextId || crypto.randomUUID(),\n status: {\n state: 'submitted',\n timestamp: new Date().toISOString(),\n message: undefined,\n },\n artifacts: [],\n history: [message],\n metadata: metadata,\n kind: 'task',\n };\n\n logger?.info(`[Task ${taskId}] Created new task.`);\n await taskStore.save({ agentId, data: initialTask });\n\n return initialTask;\n }\n\n // Handle existing task\n logger?.info(`[Task ${taskId}] Loaded existing task.`);\n\n // Add message to history and prepare updated data\n let updatedData = data;\n updatedData.history = [...(data.history || []), message];\n\n // Handle state transitions\n const { status } = data;\n const finalStates: TaskState[] = ['completed', 'failed', 'canceled'];\n\n if (finalStates.includes(status.state)) {\n logger?.warn(`[Task ${taskId}] Received message for task in final state ${status.state}. Restarting.`);\n updatedData = applyUpdateToTask(updatedData, {\n state: 'submitted',\n message: undefined,\n });\n } else if (status.state === 'input-required') {\n logger?.info(`[Task ${taskId}] Changing state from 'input-required' to 'working'.`);\n updatedData = applyUpdateToTask(updatedData, { state: 'working' });\n } else if (status.state === 'working') {\n logger?.warn(`[Task ${taskId}] Received message while already 'working'. Proceeding.`);\n }\n\n await taskStore.save({ agentId, data: updatedData });\n\n return updatedData;\n}\n\nexport function createTaskContext({\n task,\n userMessage,\n history,\n activeCancellations,\n}: {\n task: Task;\n userMessage: Message;\n history: Message[];\n activeCancellations: Set<string>;\n}): TaskContext {\n return {\n task: structuredClone(task),\n userMessage,\n history: structuredClone(history),\n isCancelled: () => activeCancellations.has(task.id),\n };\n}\n"]}
|