@mastra/client-js 0.0.0-1.x-tester-20251106055847
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 +3583 -0
- package/LICENSE.md +15 -0
- package/README.md +125 -0
- package/dist/client.d.ts +254 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/example.d.ts +2 -0
- package/dist/example.d.ts.map +1 -0
- package/dist/index.cjs +3170 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3162 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/a2a.d.ts +41 -0
- package/dist/resources/a2a.d.ts.map +1 -0
- package/dist/resources/agent-builder.d.ts +175 -0
- package/dist/resources/agent-builder.d.ts.map +1 -0
- package/dist/resources/agent.d.ts +181 -0
- package/dist/resources/agent.d.ts.map +1 -0
- package/dist/resources/base.d.ts +13 -0
- package/dist/resources/base.d.ts.map +1 -0
- package/dist/resources/index.d.ts +11 -0
- package/dist/resources/index.d.ts.map +1 -0
- package/dist/resources/mcp-tool.d.ts +28 -0
- package/dist/resources/mcp-tool.d.ts.map +1 -0
- package/dist/resources/memory-thread.d.ts +53 -0
- package/dist/resources/memory-thread.d.ts.map +1 -0
- package/dist/resources/observability.d.ts +35 -0
- package/dist/resources/observability.d.ts.map +1 -0
- package/dist/resources/tool.d.ts +24 -0
- package/dist/resources/tool.d.ts.map +1 -0
- package/dist/resources/vector.d.ts +51 -0
- package/dist/resources/vector.d.ts.map +1 -0
- package/dist/resources/workflow.d.ts +204 -0
- package/dist/resources/workflow.d.ts.map +1 -0
- package/dist/tools.d.ts +22 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/types.d.ts +451 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/index.d.ts +11 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/process-client-tools.d.ts +3 -0
- package/dist/utils/process-client-tools.d.ts.map +1 -0
- package/dist/utils/process-mastra-stream.d.ts +11 -0
- package/dist/utils/process-mastra-stream.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema.d.ts +3 -0
- package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
- package/package.json +73 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3162 @@
|
|
|
1
|
+
import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
|
|
2
|
+
import { v4 } from '@lukeed/uuid';
|
|
3
|
+
import { getErrorFromUnknown } from '@mastra/core/error';
|
|
4
|
+
import { RequestContext } from '@mastra/core/request-context';
|
|
5
|
+
import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import originalZodToJsonSchema from 'zod-to-json-schema';
|
|
8
|
+
|
|
9
|
+
// src/resources/agent.ts
|
|
10
|
+
function parseClientRequestContext(requestContext) {
|
|
11
|
+
if (requestContext) {
|
|
12
|
+
if (requestContext instanceof RequestContext) {
|
|
13
|
+
return Object.fromEntries(requestContext.entries());
|
|
14
|
+
}
|
|
15
|
+
return requestContext;
|
|
16
|
+
}
|
|
17
|
+
return void 0;
|
|
18
|
+
}
|
|
19
|
+
function base64RequestContext(requestContext) {
|
|
20
|
+
if (requestContext) {
|
|
21
|
+
return btoa(JSON.stringify(requestContext));
|
|
22
|
+
}
|
|
23
|
+
return void 0;
|
|
24
|
+
}
|
|
25
|
+
function requestContextQueryString(requestContext, delimiter = "?") {
|
|
26
|
+
const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
|
|
27
|
+
if (!requestContextParam) return "";
|
|
28
|
+
const searchParams = new URLSearchParams();
|
|
29
|
+
searchParams.set("requestContext", requestContextParam);
|
|
30
|
+
const queryString = searchParams.toString();
|
|
31
|
+
return queryString ? `${delimiter}${queryString}` : "";
|
|
32
|
+
}
|
|
33
|
+
function isZodType(value) {
|
|
34
|
+
return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
|
|
35
|
+
}
|
|
36
|
+
function zodToJsonSchema(zodSchema) {
|
|
37
|
+
if (!isZodType(zodSchema)) {
|
|
38
|
+
return zodSchema;
|
|
39
|
+
}
|
|
40
|
+
if ("toJSONSchema" in z) {
|
|
41
|
+
const fn = "toJSONSchema";
|
|
42
|
+
return z[fn].call(z, zodSchema);
|
|
43
|
+
}
|
|
44
|
+
return originalZodToJsonSchema(zodSchema, { $refStrategy: "relative" });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/utils/process-client-tools.ts
|
|
48
|
+
function processClientTools(clientTools) {
|
|
49
|
+
if (!clientTools) {
|
|
50
|
+
return void 0;
|
|
51
|
+
}
|
|
52
|
+
return Object.fromEntries(
|
|
53
|
+
Object.entries(clientTools).map(([key, value]) => {
|
|
54
|
+
if (isVercelTool(value)) {
|
|
55
|
+
return [
|
|
56
|
+
key,
|
|
57
|
+
{
|
|
58
|
+
...value,
|
|
59
|
+
parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
|
|
60
|
+
}
|
|
61
|
+
];
|
|
62
|
+
} else {
|
|
63
|
+
return [
|
|
64
|
+
key,
|
|
65
|
+
{
|
|
66
|
+
...value,
|
|
67
|
+
inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
|
|
68
|
+
outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
|
|
69
|
+
}
|
|
70
|
+
];
|
|
71
|
+
}
|
|
72
|
+
})
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/utils/process-mastra-stream.ts
|
|
77
|
+
async function sharedProcessMastraStream({
|
|
78
|
+
stream,
|
|
79
|
+
onChunk
|
|
80
|
+
}) {
|
|
81
|
+
const reader = stream.getReader();
|
|
82
|
+
const decoder = new TextDecoder();
|
|
83
|
+
let buffer = "";
|
|
84
|
+
try {
|
|
85
|
+
while (true) {
|
|
86
|
+
const { done, value } = await reader.read();
|
|
87
|
+
if (done) break;
|
|
88
|
+
buffer += decoder.decode(value, { stream: true });
|
|
89
|
+
const lines = buffer.split("\n\n");
|
|
90
|
+
buffer = lines.pop() || "";
|
|
91
|
+
for (const line of lines) {
|
|
92
|
+
if (line.startsWith("data: ")) {
|
|
93
|
+
const data = line.slice(6);
|
|
94
|
+
if (data === "[DONE]") {
|
|
95
|
+
console.info("\u{1F3C1} Stream finished");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
let json;
|
|
99
|
+
try {
|
|
100
|
+
json = JSON.parse(data);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
console.error("\u274C JSON parse error:", error, "Data:", data);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (json) {
|
|
106
|
+
await onChunk(json);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
} finally {
|
|
112
|
+
reader.releaseLock();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function processMastraNetworkStream({
|
|
116
|
+
stream,
|
|
117
|
+
onChunk
|
|
118
|
+
}) {
|
|
119
|
+
return sharedProcessMastraStream({
|
|
120
|
+
stream,
|
|
121
|
+
onChunk
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
async function processMastraStream({
|
|
125
|
+
stream,
|
|
126
|
+
onChunk
|
|
127
|
+
}) {
|
|
128
|
+
return sharedProcessMastraStream({
|
|
129
|
+
stream,
|
|
130
|
+
onChunk
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/resources/base.ts
|
|
135
|
+
var BaseResource = class {
|
|
136
|
+
options;
|
|
137
|
+
constructor(options) {
|
|
138
|
+
this.options = options;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Makes an HTTP request to the API with retries and exponential backoff
|
|
142
|
+
* @param path - The API endpoint path
|
|
143
|
+
* @param options - Optional request configuration
|
|
144
|
+
* @returns Promise containing the response data
|
|
145
|
+
*/
|
|
146
|
+
async request(path, options = {}) {
|
|
147
|
+
let lastError = null;
|
|
148
|
+
const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
|
|
149
|
+
let delay = backoffMs;
|
|
150
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
151
|
+
try {
|
|
152
|
+
const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
|
|
153
|
+
...options,
|
|
154
|
+
headers: {
|
|
155
|
+
...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
|
|
156
|
+
...headers,
|
|
157
|
+
...options.headers
|
|
158
|
+
// TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
|
|
159
|
+
// 'x-mastra-client-type': 'js',
|
|
160
|
+
},
|
|
161
|
+
signal: this.options.abortSignal,
|
|
162
|
+
credentials: options.credentials ?? credentials,
|
|
163
|
+
body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
|
|
164
|
+
});
|
|
165
|
+
if (!response.ok) {
|
|
166
|
+
const errorBody = await response.text();
|
|
167
|
+
let errorMessage = `HTTP error! status: ${response.status}`;
|
|
168
|
+
try {
|
|
169
|
+
const errorJson = JSON.parse(errorBody);
|
|
170
|
+
errorMessage += ` - ${JSON.stringify(errorJson)}`;
|
|
171
|
+
} catch {
|
|
172
|
+
if (errorBody) {
|
|
173
|
+
errorMessage += ` - ${errorBody}`;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw new Error(errorMessage);
|
|
177
|
+
}
|
|
178
|
+
if (options.stream) {
|
|
179
|
+
return response;
|
|
180
|
+
}
|
|
181
|
+
const data = await response.json();
|
|
182
|
+
return data;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
lastError = error;
|
|
185
|
+
if (attempt === retries) {
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
189
|
+
delay = Math.min(delay * 2, maxBackoffMs);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
throw lastError || new Error("Request failed");
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
// src/resources/agent.ts
|
|
197
|
+
async function executeToolCallAndRespond({
|
|
198
|
+
response,
|
|
199
|
+
params,
|
|
200
|
+
resourceId,
|
|
201
|
+
threadId,
|
|
202
|
+
requestContext,
|
|
203
|
+
respondFn
|
|
204
|
+
}) {
|
|
205
|
+
if (response.finishReason === "tool-calls") {
|
|
206
|
+
const toolCalls = response.toolCalls;
|
|
207
|
+
if (!toolCalls || !Array.isArray(toolCalls)) {
|
|
208
|
+
return response;
|
|
209
|
+
}
|
|
210
|
+
for (const toolCall of toolCalls) {
|
|
211
|
+
const clientTool = params.clientTools?.[toolCall.toolName];
|
|
212
|
+
if (clientTool && clientTool.execute) {
|
|
213
|
+
const result = await clientTool.execute(toolCall?.args, {
|
|
214
|
+
requestContext,
|
|
215
|
+
tracingContext: { currentSpan: void 0 },
|
|
216
|
+
agent: {
|
|
217
|
+
messages: response.messages,
|
|
218
|
+
toolCallId: toolCall?.toolCallId,
|
|
219
|
+
suspend: async () => {
|
|
220
|
+
},
|
|
221
|
+
threadId,
|
|
222
|
+
resourceId
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
const updatedMessages = [
|
|
226
|
+
...response.response.messages || [],
|
|
227
|
+
{
|
|
228
|
+
role: "tool",
|
|
229
|
+
content: [
|
|
230
|
+
{
|
|
231
|
+
type: "tool-result",
|
|
232
|
+
toolCallId: toolCall.toolCallId,
|
|
233
|
+
toolName: toolCall.toolName,
|
|
234
|
+
result
|
|
235
|
+
}
|
|
236
|
+
]
|
|
237
|
+
}
|
|
238
|
+
];
|
|
239
|
+
return respondFn({
|
|
240
|
+
...params,
|
|
241
|
+
messages: updatedMessages
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
var AgentVoice = class extends BaseResource {
|
|
248
|
+
constructor(options, agentId) {
|
|
249
|
+
super(options);
|
|
250
|
+
this.agentId = agentId;
|
|
251
|
+
this.agentId = agentId;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Convert text to speech using the agent's voice provider
|
|
255
|
+
* @param text - Text to convert to speech
|
|
256
|
+
* @param options - Optional provider-specific options for speech generation
|
|
257
|
+
* @returns Promise containing the audio data
|
|
258
|
+
*/
|
|
259
|
+
async speak(text, options) {
|
|
260
|
+
return this.request(`/api/agents/${this.agentId}/voice/speak`, {
|
|
261
|
+
method: "POST",
|
|
262
|
+
headers: {
|
|
263
|
+
"Content-Type": "application/json"
|
|
264
|
+
},
|
|
265
|
+
body: { input: text, options },
|
|
266
|
+
stream: true
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Convert speech to text using the agent's voice provider
|
|
271
|
+
* @param audio - Audio data to transcribe
|
|
272
|
+
* @param options - Optional provider-specific options
|
|
273
|
+
* @returns Promise containing the transcribed text
|
|
274
|
+
*/
|
|
275
|
+
listen(audio, options) {
|
|
276
|
+
const formData = new FormData();
|
|
277
|
+
formData.append("audio", audio);
|
|
278
|
+
if (options) {
|
|
279
|
+
formData.append("options", JSON.stringify(options));
|
|
280
|
+
}
|
|
281
|
+
return this.request(`/api/agents/${this.agentId}/voice/listen`, {
|
|
282
|
+
method: "POST",
|
|
283
|
+
body: formData
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Get available speakers for the agent's voice provider
|
|
288
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
289
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
290
|
+
* @returns Promise containing list of available speakers
|
|
291
|
+
*/
|
|
292
|
+
getSpeakers(requestContext) {
|
|
293
|
+
return this.request(`/api/agents/${this.agentId}/voice/speakers${requestContextQueryString(requestContext)}`);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Get the listener configuration for the agent's voice provider
|
|
297
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
298
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
299
|
+
* @returns Promise containing a check if the agent has listening capabilities
|
|
300
|
+
*/
|
|
301
|
+
getListener(requestContext) {
|
|
302
|
+
return this.request(`/api/agents/${this.agentId}/voice/listener${requestContextQueryString(requestContext)}`);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
var Agent = class extends BaseResource {
|
|
306
|
+
constructor(options, agentId) {
|
|
307
|
+
super(options);
|
|
308
|
+
this.agentId = agentId;
|
|
309
|
+
this.voice = new AgentVoice(options, this.agentId);
|
|
310
|
+
}
|
|
311
|
+
voice;
|
|
312
|
+
/**
|
|
313
|
+
* Retrieves details about the agent
|
|
314
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
315
|
+
* @returns Promise containing agent details including model and instructions
|
|
316
|
+
*/
|
|
317
|
+
details(requestContext) {
|
|
318
|
+
return this.request(`/api/agents/${this.agentId}${requestContextQueryString(requestContext)}`);
|
|
319
|
+
}
|
|
320
|
+
enhanceInstructions(instructions, comment) {
|
|
321
|
+
return this.request(`/api/agents/${this.agentId}/instructions/enhance`, {
|
|
322
|
+
method: "POST",
|
|
323
|
+
body: { instructions, comment }
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
async generateLegacy(params) {
|
|
327
|
+
const processedParams = {
|
|
328
|
+
...params,
|
|
329
|
+
output: params.output ? zodToJsonSchema(params.output) : void 0,
|
|
330
|
+
experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
|
|
331
|
+
requestContext: parseClientRequestContext(params.requestContext),
|
|
332
|
+
clientTools: processClientTools(params.clientTools)
|
|
333
|
+
};
|
|
334
|
+
const { resourceId, threadId, requestContext } = processedParams;
|
|
335
|
+
const response = await this.request(
|
|
336
|
+
`/api/agents/${this.agentId}/generate-legacy`,
|
|
337
|
+
{
|
|
338
|
+
method: "POST",
|
|
339
|
+
body: processedParams
|
|
340
|
+
}
|
|
341
|
+
);
|
|
342
|
+
if (response.finishReason === "tool-calls") {
|
|
343
|
+
const toolCalls = response.toolCalls;
|
|
344
|
+
if (!toolCalls || !Array.isArray(toolCalls)) {
|
|
345
|
+
return response;
|
|
346
|
+
}
|
|
347
|
+
for (const toolCall of toolCalls) {
|
|
348
|
+
const clientTool = params.clientTools?.[toolCall.toolName];
|
|
349
|
+
if (clientTool && clientTool.execute) {
|
|
350
|
+
const result = await clientTool.execute(toolCall?.args, {
|
|
351
|
+
requestContext,
|
|
352
|
+
tracingContext: { currentSpan: void 0 },
|
|
353
|
+
agent: {
|
|
354
|
+
messages: response.messages,
|
|
355
|
+
toolCallId: toolCall?.toolCallId,
|
|
356
|
+
suspend: async () => {
|
|
357
|
+
},
|
|
358
|
+
threadId,
|
|
359
|
+
resourceId
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
const updatedMessages = [
|
|
363
|
+
...response.response.messages,
|
|
364
|
+
{
|
|
365
|
+
role: "tool",
|
|
366
|
+
content: [
|
|
367
|
+
{
|
|
368
|
+
type: "tool-result",
|
|
369
|
+
toolCallId: toolCall.toolCallId,
|
|
370
|
+
toolName: toolCall.toolName,
|
|
371
|
+
result
|
|
372
|
+
}
|
|
373
|
+
]
|
|
374
|
+
}
|
|
375
|
+
];
|
|
376
|
+
return this.generate({
|
|
377
|
+
...params,
|
|
378
|
+
messages: updatedMessages
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return response;
|
|
384
|
+
}
|
|
385
|
+
async generate(messagesOrParams, options) {
|
|
386
|
+
let params;
|
|
387
|
+
if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
|
|
388
|
+
params = messagesOrParams;
|
|
389
|
+
} else {
|
|
390
|
+
params = {
|
|
391
|
+
messages: messagesOrParams,
|
|
392
|
+
...options
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const processedParams = {
|
|
396
|
+
...params,
|
|
397
|
+
requestContext: parseClientRequestContext(params.requestContext),
|
|
398
|
+
clientTools: processClientTools(params.clientTools),
|
|
399
|
+
structuredOutput: params.structuredOutput ? {
|
|
400
|
+
...params.structuredOutput,
|
|
401
|
+
schema: zodToJsonSchema(params.structuredOutput.schema)
|
|
402
|
+
} : void 0
|
|
403
|
+
};
|
|
404
|
+
const { resourceId, threadId, requestContext } = processedParams;
|
|
405
|
+
const response = await this.request(
|
|
406
|
+
`/api/agents/${this.agentId}/generate`,
|
|
407
|
+
{
|
|
408
|
+
method: "POST",
|
|
409
|
+
body: processedParams
|
|
410
|
+
}
|
|
411
|
+
);
|
|
412
|
+
if (response.finishReason === "tool-calls") {
|
|
413
|
+
return executeToolCallAndRespond({
|
|
414
|
+
response,
|
|
415
|
+
params,
|
|
416
|
+
resourceId,
|
|
417
|
+
threadId,
|
|
418
|
+
requestContext,
|
|
419
|
+
respondFn: this.generate.bind(this)
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return response;
|
|
423
|
+
}
|
|
424
|
+
async processChatResponse({
|
|
425
|
+
stream,
|
|
426
|
+
update,
|
|
427
|
+
onToolCall,
|
|
428
|
+
onFinish,
|
|
429
|
+
getCurrentDate = () => /* @__PURE__ */ new Date(),
|
|
430
|
+
lastMessage
|
|
431
|
+
}) {
|
|
432
|
+
const replaceLastMessage = lastMessage?.role === "assistant";
|
|
433
|
+
let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
|
|
434
|
+
(lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
|
|
435
|
+
return Math.max(max, toolInvocation.step ?? 0);
|
|
436
|
+
}, 0) ?? 0) : 0;
|
|
437
|
+
const message = replaceLastMessage ? structuredClone(lastMessage) : {
|
|
438
|
+
id: v4(),
|
|
439
|
+
createdAt: getCurrentDate(),
|
|
440
|
+
role: "assistant",
|
|
441
|
+
content: "",
|
|
442
|
+
parts: []
|
|
443
|
+
};
|
|
444
|
+
let currentTextPart = void 0;
|
|
445
|
+
let currentReasoningPart = void 0;
|
|
446
|
+
let currentReasoningTextDetail = void 0;
|
|
447
|
+
function updateToolInvocationPart(toolCallId, invocation) {
|
|
448
|
+
const part = message.parts.find(
|
|
449
|
+
(part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
|
|
450
|
+
);
|
|
451
|
+
if (part != null) {
|
|
452
|
+
part.toolInvocation = invocation;
|
|
453
|
+
} else {
|
|
454
|
+
message.parts.push({
|
|
455
|
+
type: "tool-invocation",
|
|
456
|
+
toolInvocation: invocation
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
const data = [];
|
|
461
|
+
let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
|
|
462
|
+
const partialToolCalls = {};
|
|
463
|
+
let usage = {
|
|
464
|
+
completionTokens: NaN,
|
|
465
|
+
promptTokens: NaN,
|
|
466
|
+
totalTokens: NaN
|
|
467
|
+
};
|
|
468
|
+
let finishReason = "unknown";
|
|
469
|
+
function execUpdate() {
|
|
470
|
+
const copiedData = [...data];
|
|
471
|
+
if (messageAnnotations?.length) {
|
|
472
|
+
message.annotations = messageAnnotations;
|
|
473
|
+
}
|
|
474
|
+
const copiedMessage = {
|
|
475
|
+
// deep copy the message to ensure that deep changes (msg attachments) are updated
|
|
476
|
+
// with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
|
|
477
|
+
...structuredClone(message),
|
|
478
|
+
// add a revision id to ensure that the message is updated with SWR. SWR uses a
|
|
479
|
+
// hashing approach by default to detect changes, but it only works for shallow
|
|
480
|
+
// changes. This is why we need to add a revision id to ensure that the message
|
|
481
|
+
// is updated with SWR (without it, the changes get stuck in SWR and are not
|
|
482
|
+
// forwarded to rendering):
|
|
483
|
+
revisionId: v4()
|
|
484
|
+
};
|
|
485
|
+
update({
|
|
486
|
+
message: copiedMessage,
|
|
487
|
+
data: copiedData,
|
|
488
|
+
replaceLastMessage
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
await processDataStream({
|
|
492
|
+
stream,
|
|
493
|
+
onTextPart(value) {
|
|
494
|
+
if (currentTextPart == null) {
|
|
495
|
+
currentTextPart = {
|
|
496
|
+
type: "text",
|
|
497
|
+
text: value
|
|
498
|
+
};
|
|
499
|
+
message.parts.push(currentTextPart);
|
|
500
|
+
} else {
|
|
501
|
+
currentTextPart.text += value;
|
|
502
|
+
}
|
|
503
|
+
message.content += value;
|
|
504
|
+
execUpdate();
|
|
505
|
+
},
|
|
506
|
+
onReasoningPart(value) {
|
|
507
|
+
if (currentReasoningTextDetail == null) {
|
|
508
|
+
currentReasoningTextDetail = { type: "text", text: value };
|
|
509
|
+
if (currentReasoningPart != null) {
|
|
510
|
+
currentReasoningPart.details.push(currentReasoningTextDetail);
|
|
511
|
+
}
|
|
512
|
+
} else {
|
|
513
|
+
currentReasoningTextDetail.text += value;
|
|
514
|
+
}
|
|
515
|
+
if (currentReasoningPart == null) {
|
|
516
|
+
currentReasoningPart = {
|
|
517
|
+
type: "reasoning",
|
|
518
|
+
reasoning: value,
|
|
519
|
+
details: [currentReasoningTextDetail]
|
|
520
|
+
};
|
|
521
|
+
message.parts.push(currentReasoningPart);
|
|
522
|
+
} else {
|
|
523
|
+
currentReasoningPart.reasoning += value;
|
|
524
|
+
}
|
|
525
|
+
message.reasoning = (message.reasoning ?? "") + value;
|
|
526
|
+
execUpdate();
|
|
527
|
+
},
|
|
528
|
+
onReasoningSignaturePart(value) {
|
|
529
|
+
if (currentReasoningTextDetail != null) {
|
|
530
|
+
currentReasoningTextDetail.signature = value.signature;
|
|
531
|
+
}
|
|
532
|
+
},
|
|
533
|
+
onRedactedReasoningPart(value) {
|
|
534
|
+
if (currentReasoningPart == null) {
|
|
535
|
+
currentReasoningPart = {
|
|
536
|
+
type: "reasoning",
|
|
537
|
+
reasoning: "",
|
|
538
|
+
details: []
|
|
539
|
+
};
|
|
540
|
+
message.parts.push(currentReasoningPart);
|
|
541
|
+
}
|
|
542
|
+
currentReasoningPart.details.push({
|
|
543
|
+
type: "redacted",
|
|
544
|
+
data: value.data
|
|
545
|
+
});
|
|
546
|
+
currentReasoningTextDetail = void 0;
|
|
547
|
+
execUpdate();
|
|
548
|
+
},
|
|
549
|
+
onFilePart(value) {
|
|
550
|
+
message.parts.push({
|
|
551
|
+
type: "file",
|
|
552
|
+
mimeType: value.mimeType,
|
|
553
|
+
data: value.data
|
|
554
|
+
});
|
|
555
|
+
execUpdate();
|
|
556
|
+
},
|
|
557
|
+
onSourcePart(value) {
|
|
558
|
+
message.parts.push({
|
|
559
|
+
type: "source",
|
|
560
|
+
source: value
|
|
561
|
+
});
|
|
562
|
+
execUpdate();
|
|
563
|
+
},
|
|
564
|
+
onToolCallStreamingStartPart(value) {
|
|
565
|
+
if (message.toolInvocations == null) {
|
|
566
|
+
message.toolInvocations = [];
|
|
567
|
+
}
|
|
568
|
+
partialToolCalls[value.toolCallId] = {
|
|
569
|
+
text: "",
|
|
570
|
+
step,
|
|
571
|
+
toolName: value.toolName,
|
|
572
|
+
index: message.toolInvocations.length
|
|
573
|
+
};
|
|
574
|
+
const invocation = {
|
|
575
|
+
state: "partial-call",
|
|
576
|
+
step,
|
|
577
|
+
toolCallId: value.toolCallId,
|
|
578
|
+
toolName: value.toolName,
|
|
579
|
+
args: void 0
|
|
580
|
+
};
|
|
581
|
+
message.toolInvocations.push(invocation);
|
|
582
|
+
updateToolInvocationPart(value.toolCallId, invocation);
|
|
583
|
+
execUpdate();
|
|
584
|
+
},
|
|
585
|
+
onToolCallDeltaPart(value) {
|
|
586
|
+
const partialToolCall = partialToolCalls[value.toolCallId];
|
|
587
|
+
partialToolCall.text += value.argsTextDelta;
|
|
588
|
+
const { value: partialArgs } = parsePartialJson(partialToolCall.text);
|
|
589
|
+
const invocation = {
|
|
590
|
+
state: "partial-call",
|
|
591
|
+
step: partialToolCall.step,
|
|
592
|
+
toolCallId: value.toolCallId,
|
|
593
|
+
toolName: partialToolCall.toolName,
|
|
594
|
+
args: partialArgs
|
|
595
|
+
};
|
|
596
|
+
message.toolInvocations[partialToolCall.index] = invocation;
|
|
597
|
+
updateToolInvocationPart(value.toolCallId, invocation);
|
|
598
|
+
execUpdate();
|
|
599
|
+
},
|
|
600
|
+
async onToolCallPart(value) {
|
|
601
|
+
const invocation = {
|
|
602
|
+
state: "call",
|
|
603
|
+
step,
|
|
604
|
+
...value
|
|
605
|
+
};
|
|
606
|
+
if (partialToolCalls[value.toolCallId] != null) {
|
|
607
|
+
message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
|
|
608
|
+
} else {
|
|
609
|
+
if (message.toolInvocations == null) {
|
|
610
|
+
message.toolInvocations = [];
|
|
611
|
+
}
|
|
612
|
+
message.toolInvocations.push(invocation);
|
|
613
|
+
}
|
|
614
|
+
updateToolInvocationPart(value.toolCallId, invocation);
|
|
615
|
+
execUpdate();
|
|
616
|
+
if (onToolCall) {
|
|
617
|
+
const result = await onToolCall({ toolCall: value });
|
|
618
|
+
if (result != null) {
|
|
619
|
+
const invocation2 = {
|
|
620
|
+
state: "result",
|
|
621
|
+
step,
|
|
622
|
+
...value,
|
|
623
|
+
result
|
|
624
|
+
};
|
|
625
|
+
message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
|
|
626
|
+
updateToolInvocationPart(value.toolCallId, invocation2);
|
|
627
|
+
execUpdate();
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
},
|
|
631
|
+
onToolResultPart(value) {
|
|
632
|
+
const toolInvocations = message.toolInvocations;
|
|
633
|
+
if (toolInvocations == null) {
|
|
634
|
+
throw new Error("tool_result must be preceded by a tool_call");
|
|
635
|
+
}
|
|
636
|
+
const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
|
|
637
|
+
if (toolInvocationIndex === -1) {
|
|
638
|
+
throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
|
|
639
|
+
}
|
|
640
|
+
const invocation = {
|
|
641
|
+
...toolInvocations[toolInvocationIndex],
|
|
642
|
+
state: "result",
|
|
643
|
+
...value
|
|
644
|
+
};
|
|
645
|
+
toolInvocations[toolInvocationIndex] = invocation;
|
|
646
|
+
updateToolInvocationPart(value.toolCallId, invocation);
|
|
647
|
+
execUpdate();
|
|
648
|
+
},
|
|
649
|
+
onDataPart(value) {
|
|
650
|
+
data.push(...value);
|
|
651
|
+
execUpdate();
|
|
652
|
+
},
|
|
653
|
+
onMessageAnnotationsPart(value) {
|
|
654
|
+
if (messageAnnotations == null) {
|
|
655
|
+
messageAnnotations = [...value];
|
|
656
|
+
} else {
|
|
657
|
+
messageAnnotations.push(...value);
|
|
658
|
+
}
|
|
659
|
+
execUpdate();
|
|
660
|
+
},
|
|
661
|
+
onFinishStepPart(value) {
|
|
662
|
+
step += 1;
|
|
663
|
+
currentTextPart = value.isContinued ? currentTextPart : void 0;
|
|
664
|
+
currentReasoningPart = void 0;
|
|
665
|
+
currentReasoningTextDetail = void 0;
|
|
666
|
+
},
|
|
667
|
+
onStartStepPart(value) {
|
|
668
|
+
if (!replaceLastMessage) {
|
|
669
|
+
message.id = value.messageId;
|
|
670
|
+
}
|
|
671
|
+
message.parts.push({ type: "step-start" });
|
|
672
|
+
execUpdate();
|
|
673
|
+
},
|
|
674
|
+
onFinishMessagePart(value) {
|
|
675
|
+
finishReason = value.finishReason;
|
|
676
|
+
if (value.usage != null) {
|
|
677
|
+
usage = value.usage;
|
|
678
|
+
}
|
|
679
|
+
},
|
|
680
|
+
onErrorPart(error) {
|
|
681
|
+
throw new Error(error);
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
onFinish?.({ message, finishReason, usage });
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Streams a response from the agent
|
|
688
|
+
* @param params - Stream parameters including prompt
|
|
689
|
+
* @returns Promise containing the enhanced Response object with processDataStream method
|
|
690
|
+
*/
|
|
691
|
+
async streamLegacy(params) {
|
|
692
|
+
const processedParams = {
|
|
693
|
+
...params,
|
|
694
|
+
output: params.output ? zodToJsonSchema(params.output) : void 0,
|
|
695
|
+
experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
|
|
696
|
+
requestContext: parseClientRequestContext(params.requestContext),
|
|
697
|
+
clientTools: processClientTools(params.clientTools)
|
|
698
|
+
};
|
|
699
|
+
const { readable, writable } = new TransformStream();
|
|
700
|
+
const response = await this.processStreamResponseLegacy(processedParams, writable);
|
|
701
|
+
const streamResponse = new Response(readable, {
|
|
702
|
+
status: response.status,
|
|
703
|
+
statusText: response.statusText,
|
|
704
|
+
headers: response.headers
|
|
705
|
+
});
|
|
706
|
+
streamResponse.processDataStream = async (options = {}) => {
|
|
707
|
+
await processDataStream({
|
|
708
|
+
stream: streamResponse.body,
|
|
709
|
+
...options
|
|
710
|
+
});
|
|
711
|
+
};
|
|
712
|
+
return streamResponse;
|
|
713
|
+
}
|
|
714
|
+
async processChatResponse_vNext({
|
|
715
|
+
stream,
|
|
716
|
+
update,
|
|
717
|
+
onToolCall,
|
|
718
|
+
onFinish,
|
|
719
|
+
getCurrentDate = () => /* @__PURE__ */ new Date(),
|
|
720
|
+
lastMessage
|
|
721
|
+
}) {
|
|
722
|
+
const replaceLastMessage = lastMessage?.role === "assistant";
|
|
723
|
+
let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
|
|
724
|
+
(lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
|
|
725
|
+
return Math.max(max, toolInvocation.step ?? 0);
|
|
726
|
+
}, 0) ?? 0) : 0;
|
|
727
|
+
const message = replaceLastMessage ? structuredClone(lastMessage) : {
|
|
728
|
+
id: v4(),
|
|
729
|
+
createdAt: getCurrentDate(),
|
|
730
|
+
role: "assistant",
|
|
731
|
+
content: "",
|
|
732
|
+
parts: []
|
|
733
|
+
};
|
|
734
|
+
let currentTextPart = void 0;
|
|
735
|
+
let currentReasoningPart = void 0;
|
|
736
|
+
let currentReasoningTextDetail = void 0;
|
|
737
|
+
function updateToolInvocationPart(toolCallId, invocation) {
|
|
738
|
+
const part = message.parts.find(
|
|
739
|
+
(part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
|
|
740
|
+
);
|
|
741
|
+
if (part != null) {
|
|
742
|
+
part.toolInvocation = invocation;
|
|
743
|
+
} else {
|
|
744
|
+
message.parts.push({
|
|
745
|
+
type: "tool-invocation",
|
|
746
|
+
toolInvocation: invocation
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
const data = [];
|
|
751
|
+
let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
|
|
752
|
+
const partialToolCalls = {};
|
|
753
|
+
let usage = {
|
|
754
|
+
completionTokens: NaN,
|
|
755
|
+
promptTokens: NaN,
|
|
756
|
+
totalTokens: NaN
|
|
757
|
+
};
|
|
758
|
+
let finishReason = "unknown";
|
|
759
|
+
function execUpdate() {
|
|
760
|
+
const copiedData = [...data];
|
|
761
|
+
if (messageAnnotations?.length) {
|
|
762
|
+
message.annotations = messageAnnotations;
|
|
763
|
+
}
|
|
764
|
+
const copiedMessage = {
|
|
765
|
+
// deep copy the message to ensure that deep changes (msg attachments) are updated
|
|
766
|
+
// with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
|
|
767
|
+
...structuredClone(message),
|
|
768
|
+
// add a revision id to ensure that the message is updated with SWR. SWR uses a
|
|
769
|
+
// hashing approach by default to detect changes, but it only works for shallow
|
|
770
|
+
// changes. This is why we need to add a revision id to ensure that the message
|
|
771
|
+
// is updated with SWR (without it, the changes get stuck in SWR and are not
|
|
772
|
+
// forwarded to rendering):
|
|
773
|
+
revisionId: v4()
|
|
774
|
+
};
|
|
775
|
+
update({
|
|
776
|
+
message: copiedMessage,
|
|
777
|
+
data: copiedData,
|
|
778
|
+
replaceLastMessage
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
await processMastraStream({
|
|
782
|
+
stream,
|
|
783
|
+
// TODO: casting as any here because the stream types were all typed as any before in core.
|
|
784
|
+
// but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
|
|
785
|
+
onChunk: async (chunk) => {
|
|
786
|
+
switch (chunk.type) {
|
|
787
|
+
case "tripwire": {
|
|
788
|
+
message.parts.push({
|
|
789
|
+
type: "text",
|
|
790
|
+
text: chunk.payload.tripwireReason
|
|
791
|
+
});
|
|
792
|
+
execUpdate();
|
|
793
|
+
break;
|
|
794
|
+
}
|
|
795
|
+
case "step-start": {
|
|
796
|
+
if (!replaceLastMessage) {
|
|
797
|
+
message.id = chunk.payload.messageId;
|
|
798
|
+
}
|
|
799
|
+
message.parts.push({ type: "step-start" });
|
|
800
|
+
execUpdate();
|
|
801
|
+
break;
|
|
802
|
+
}
|
|
803
|
+
case "text-delta": {
|
|
804
|
+
if (currentTextPart == null) {
|
|
805
|
+
currentTextPart = {
|
|
806
|
+
type: "text",
|
|
807
|
+
text: chunk.payload.text
|
|
808
|
+
};
|
|
809
|
+
message.parts.push(currentTextPart);
|
|
810
|
+
} else {
|
|
811
|
+
currentTextPart.text += chunk.payload.text;
|
|
812
|
+
}
|
|
813
|
+
message.content += chunk.payload.text;
|
|
814
|
+
execUpdate();
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
case "reasoning-delta": {
|
|
818
|
+
if (currentReasoningTextDetail == null) {
|
|
819
|
+
currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
|
|
820
|
+
if (currentReasoningPart != null) {
|
|
821
|
+
currentReasoningPart.details.push(currentReasoningTextDetail);
|
|
822
|
+
}
|
|
823
|
+
} else {
|
|
824
|
+
currentReasoningTextDetail.text += chunk.payload.text;
|
|
825
|
+
}
|
|
826
|
+
if (currentReasoningPart == null) {
|
|
827
|
+
currentReasoningPart = {
|
|
828
|
+
type: "reasoning",
|
|
829
|
+
reasoning: chunk.payload.text,
|
|
830
|
+
details: [currentReasoningTextDetail]
|
|
831
|
+
};
|
|
832
|
+
message.parts.push(currentReasoningPart);
|
|
833
|
+
} else {
|
|
834
|
+
currentReasoningPart.reasoning += chunk.payload.text;
|
|
835
|
+
}
|
|
836
|
+
message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
|
|
837
|
+
execUpdate();
|
|
838
|
+
break;
|
|
839
|
+
}
|
|
840
|
+
case "file": {
|
|
841
|
+
message.parts.push({
|
|
842
|
+
type: "file",
|
|
843
|
+
mimeType: chunk.payload.mimeType,
|
|
844
|
+
data: chunk.payload.data
|
|
845
|
+
});
|
|
846
|
+
execUpdate();
|
|
847
|
+
break;
|
|
848
|
+
}
|
|
849
|
+
case "source": {
|
|
850
|
+
message.parts.push({
|
|
851
|
+
type: "source",
|
|
852
|
+
source: chunk.payload.source
|
|
853
|
+
});
|
|
854
|
+
execUpdate();
|
|
855
|
+
break;
|
|
856
|
+
}
|
|
857
|
+
case "tool-call": {
|
|
858
|
+
const invocation = {
|
|
859
|
+
state: "call",
|
|
860
|
+
step,
|
|
861
|
+
...chunk.payload
|
|
862
|
+
};
|
|
863
|
+
if (partialToolCalls[chunk.payload.toolCallId] != null) {
|
|
864
|
+
message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
|
|
865
|
+
} else {
|
|
866
|
+
if (message.toolInvocations == null) {
|
|
867
|
+
message.toolInvocations = [];
|
|
868
|
+
}
|
|
869
|
+
message.toolInvocations.push(invocation);
|
|
870
|
+
}
|
|
871
|
+
updateToolInvocationPart(chunk.payload.toolCallId, invocation);
|
|
872
|
+
execUpdate();
|
|
873
|
+
if (onToolCall) {
|
|
874
|
+
const result = await onToolCall({ toolCall: chunk.payload });
|
|
875
|
+
if (result != null) {
|
|
876
|
+
const invocation2 = {
|
|
877
|
+
state: "result",
|
|
878
|
+
step,
|
|
879
|
+
...chunk.payload,
|
|
880
|
+
result
|
|
881
|
+
};
|
|
882
|
+
message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
|
|
883
|
+
updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
|
|
884
|
+
execUpdate();
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
case "tool-call-input-streaming-start": {
|
|
889
|
+
if (message.toolInvocations == null) {
|
|
890
|
+
message.toolInvocations = [];
|
|
891
|
+
}
|
|
892
|
+
partialToolCalls[chunk.payload.toolCallId] = {
|
|
893
|
+
text: "",
|
|
894
|
+
step,
|
|
895
|
+
toolName: chunk.payload.toolName,
|
|
896
|
+
index: message.toolInvocations.length
|
|
897
|
+
};
|
|
898
|
+
const invocation = {
|
|
899
|
+
state: "partial-call",
|
|
900
|
+
step,
|
|
901
|
+
toolCallId: chunk.payload.toolCallId,
|
|
902
|
+
toolName: chunk.payload.toolName,
|
|
903
|
+
args: chunk.payload.args
|
|
904
|
+
};
|
|
905
|
+
message.toolInvocations.push(invocation);
|
|
906
|
+
updateToolInvocationPart(chunk.payload.toolCallId, invocation);
|
|
907
|
+
execUpdate();
|
|
908
|
+
break;
|
|
909
|
+
}
|
|
910
|
+
case "tool-call-delta": {
|
|
911
|
+
const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
|
|
912
|
+
partialToolCall.text += chunk.payload.argsTextDelta;
|
|
913
|
+
const { value: partialArgs } = parsePartialJson(partialToolCall.text);
|
|
914
|
+
const invocation = {
|
|
915
|
+
state: "partial-call",
|
|
916
|
+
step: partialToolCall.step,
|
|
917
|
+
toolCallId: chunk.payload.toolCallId,
|
|
918
|
+
toolName: partialToolCall.toolName,
|
|
919
|
+
args: partialArgs
|
|
920
|
+
};
|
|
921
|
+
message.toolInvocations[partialToolCall.index] = invocation;
|
|
922
|
+
updateToolInvocationPart(chunk.payload.toolCallId, invocation);
|
|
923
|
+
execUpdate();
|
|
924
|
+
break;
|
|
925
|
+
}
|
|
926
|
+
case "tool-result": {
|
|
927
|
+
const toolInvocations = message.toolInvocations;
|
|
928
|
+
if (toolInvocations == null) {
|
|
929
|
+
throw new Error("tool_result must be preceded by a tool_call");
|
|
930
|
+
}
|
|
931
|
+
const toolInvocationIndex = toolInvocations.findIndex(
|
|
932
|
+
(invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
|
|
933
|
+
);
|
|
934
|
+
if (toolInvocationIndex === -1) {
|
|
935
|
+
throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
|
|
936
|
+
}
|
|
937
|
+
const invocation = {
|
|
938
|
+
...toolInvocations[toolInvocationIndex],
|
|
939
|
+
state: "result",
|
|
940
|
+
...chunk.payload
|
|
941
|
+
};
|
|
942
|
+
toolInvocations[toolInvocationIndex] = invocation;
|
|
943
|
+
updateToolInvocationPart(chunk.payload.toolCallId, invocation);
|
|
944
|
+
execUpdate();
|
|
945
|
+
break;
|
|
946
|
+
}
|
|
947
|
+
case "error": {
|
|
948
|
+
throw getErrorFromUnknown(chunk.payload.error, {
|
|
949
|
+
fallbackMessage: "Unknown error in stream",
|
|
950
|
+
supportSerialization: false
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
case "data": {
|
|
954
|
+
data.push(...chunk.payload.data);
|
|
955
|
+
execUpdate();
|
|
956
|
+
break;
|
|
957
|
+
}
|
|
958
|
+
case "step-finish": {
|
|
959
|
+
step += 1;
|
|
960
|
+
currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
|
|
961
|
+
currentReasoningPart = void 0;
|
|
962
|
+
currentReasoningTextDetail = void 0;
|
|
963
|
+
execUpdate();
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
case "finish": {
|
|
967
|
+
finishReason = chunk.payload.stepResult.reason;
|
|
968
|
+
if (chunk.payload.usage != null) {
|
|
969
|
+
usage = chunk.payload.usage;
|
|
970
|
+
}
|
|
971
|
+
break;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
onFinish?.({ message, finishReason, usage });
|
|
977
|
+
}
|
|
978
|
+
async processStreamResponse(processedParams, writable, route = "stream") {
|
|
979
|
+
const response = await this.request(`/api/agents/${this.agentId}/${route}`, {
|
|
980
|
+
method: "POST",
|
|
981
|
+
body: processedParams,
|
|
982
|
+
stream: true
|
|
983
|
+
});
|
|
984
|
+
if (!response.body) {
|
|
985
|
+
throw new Error("No response body");
|
|
986
|
+
}
|
|
987
|
+
try {
|
|
988
|
+
let toolCalls = [];
|
|
989
|
+
let messages = [];
|
|
990
|
+
const [streamForWritable, streamForProcessing] = response.body.tee();
|
|
991
|
+
streamForWritable.pipeTo(
|
|
992
|
+
new WritableStream({
|
|
993
|
+
async write(chunk) {
|
|
994
|
+
let writer;
|
|
995
|
+
try {
|
|
996
|
+
writer = writable.getWriter();
|
|
997
|
+
const text = new TextDecoder().decode(chunk);
|
|
998
|
+
const lines = text.split("\n\n");
|
|
999
|
+
const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
|
|
1000
|
+
await writer.write(new TextEncoder().encode(readableLines));
|
|
1001
|
+
} catch {
|
|
1002
|
+
await writer?.write(chunk);
|
|
1003
|
+
} finally {
|
|
1004
|
+
writer?.releaseLock();
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}),
|
|
1008
|
+
{
|
|
1009
|
+
preventClose: true
|
|
1010
|
+
}
|
|
1011
|
+
).catch((error) => {
|
|
1012
|
+
console.error("Error piping to writable stream:", error);
|
|
1013
|
+
});
|
|
1014
|
+
this.processChatResponse_vNext({
|
|
1015
|
+
stream: streamForProcessing,
|
|
1016
|
+
update: ({ message }) => {
|
|
1017
|
+
const existingIndex = messages.findIndex((m) => m.id === message.id);
|
|
1018
|
+
if (existingIndex !== -1) {
|
|
1019
|
+
messages[existingIndex] = message;
|
|
1020
|
+
} else {
|
|
1021
|
+
messages.push(message);
|
|
1022
|
+
}
|
|
1023
|
+
},
|
|
1024
|
+
onFinish: async ({ finishReason, message }) => {
|
|
1025
|
+
if (finishReason === "tool-calls") {
|
|
1026
|
+
const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
|
|
1027
|
+
if (toolCall) {
|
|
1028
|
+
toolCalls.push(toolCall);
|
|
1029
|
+
}
|
|
1030
|
+
let shouldExecuteClientTool = false;
|
|
1031
|
+
for (const toolCall2 of toolCalls) {
|
|
1032
|
+
const clientTool = processedParams.clientTools?.[toolCall2.toolName];
|
|
1033
|
+
if (clientTool && clientTool.execute) {
|
|
1034
|
+
shouldExecuteClientTool = true;
|
|
1035
|
+
const result = await clientTool.execute(toolCall2?.args, {
|
|
1036
|
+
requestContext: processedParams.requestContext,
|
|
1037
|
+
// TODO: Pass proper tracing context when client-js supports tracing
|
|
1038
|
+
tracingContext: { currentSpan: void 0 },
|
|
1039
|
+
agent: {
|
|
1040
|
+
messages: response.messages,
|
|
1041
|
+
toolCallId: toolCall2?.toolCallId,
|
|
1042
|
+
suspend: async () => {
|
|
1043
|
+
},
|
|
1044
|
+
threadId: processedParams.threadId,
|
|
1045
|
+
resourceId: processedParams.resourceId
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
const lastMessageRaw = messages[messages.length - 1];
|
|
1049
|
+
const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
|
|
1050
|
+
const toolInvocationPart = lastMessage?.parts?.find(
|
|
1051
|
+
(part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
|
|
1052
|
+
);
|
|
1053
|
+
if (toolInvocationPart) {
|
|
1054
|
+
toolInvocationPart.toolInvocation = {
|
|
1055
|
+
...toolInvocationPart.toolInvocation,
|
|
1056
|
+
state: "result",
|
|
1057
|
+
result
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
const toolInvocation = lastMessage?.toolInvocations?.find(
|
|
1061
|
+
(toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
|
|
1062
|
+
);
|
|
1063
|
+
if (toolInvocation) {
|
|
1064
|
+
toolInvocation.state = "result";
|
|
1065
|
+
toolInvocation.result = result;
|
|
1066
|
+
}
|
|
1067
|
+
const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
|
|
1068
|
+
this.processStreamResponse(
|
|
1069
|
+
{
|
|
1070
|
+
...processedParams,
|
|
1071
|
+
messages: updatedMessages
|
|
1072
|
+
},
|
|
1073
|
+
writable
|
|
1074
|
+
).catch((error) => {
|
|
1075
|
+
console.error("Error processing stream response:", error);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
if (!shouldExecuteClientTool) {
|
|
1080
|
+
setTimeout(() => {
|
|
1081
|
+
writable.close();
|
|
1082
|
+
}, 0);
|
|
1083
|
+
}
|
|
1084
|
+
} else {
|
|
1085
|
+
setTimeout(() => {
|
|
1086
|
+
writable.close();
|
|
1087
|
+
}, 0);
|
|
1088
|
+
}
|
|
1089
|
+
},
|
|
1090
|
+
lastMessage: void 0
|
|
1091
|
+
}).catch((error) => {
|
|
1092
|
+
console.error("Error processing stream response:", error);
|
|
1093
|
+
});
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
console.error("Error processing stream response:", error);
|
|
1096
|
+
}
|
|
1097
|
+
return response;
|
|
1098
|
+
}
|
|
1099
|
+
async network(params) {
|
|
1100
|
+
const response = await this.request(`/api/agents/${this.agentId}/network`, {
|
|
1101
|
+
method: "POST",
|
|
1102
|
+
body: params,
|
|
1103
|
+
stream: true
|
|
1104
|
+
});
|
|
1105
|
+
if (!response.body) {
|
|
1106
|
+
throw new Error("No response body");
|
|
1107
|
+
}
|
|
1108
|
+
const streamResponse = new Response(response.body, {
|
|
1109
|
+
status: response.status,
|
|
1110
|
+
statusText: response.statusText,
|
|
1111
|
+
headers: response.headers
|
|
1112
|
+
});
|
|
1113
|
+
streamResponse.processDataStream = async ({
|
|
1114
|
+
onChunk
|
|
1115
|
+
}) => {
|
|
1116
|
+
await processMastraNetworkStream({
|
|
1117
|
+
stream: streamResponse.body,
|
|
1118
|
+
onChunk
|
|
1119
|
+
});
|
|
1120
|
+
};
|
|
1121
|
+
return streamResponse;
|
|
1122
|
+
}
|
|
1123
|
+
async stream(messagesOrParams, options) {
|
|
1124
|
+
let params;
|
|
1125
|
+
if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
|
|
1126
|
+
params = messagesOrParams;
|
|
1127
|
+
} else {
|
|
1128
|
+
params = {
|
|
1129
|
+
messages: messagesOrParams,
|
|
1130
|
+
...options
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
const processedParams = {
|
|
1134
|
+
...params,
|
|
1135
|
+
requestContext: parseClientRequestContext(params.requestContext),
|
|
1136
|
+
clientTools: processClientTools(params.clientTools),
|
|
1137
|
+
structuredOutput: params.structuredOutput ? {
|
|
1138
|
+
...params.structuredOutput,
|
|
1139
|
+
schema: zodToJsonSchema(params.structuredOutput.schema)
|
|
1140
|
+
} : void 0
|
|
1141
|
+
};
|
|
1142
|
+
const { readable, writable } = new TransformStream();
|
|
1143
|
+
const response = await this.processStreamResponse(processedParams, writable);
|
|
1144
|
+
const streamResponse = new Response(readable, {
|
|
1145
|
+
status: response.status,
|
|
1146
|
+
statusText: response.statusText,
|
|
1147
|
+
headers: response.headers
|
|
1148
|
+
});
|
|
1149
|
+
streamResponse.processDataStream = async ({
|
|
1150
|
+
onChunk
|
|
1151
|
+
}) => {
|
|
1152
|
+
await processMastraStream({
|
|
1153
|
+
stream: streamResponse.body,
|
|
1154
|
+
onChunk
|
|
1155
|
+
});
|
|
1156
|
+
};
|
|
1157
|
+
return streamResponse;
|
|
1158
|
+
}
|
|
1159
|
+
async approveToolCall(params) {
|
|
1160
|
+
const { readable, writable } = new TransformStream();
|
|
1161
|
+
const response = await this.processStreamResponse(params, writable, "approve-tool-call");
|
|
1162
|
+
const streamResponse = new Response(readable, {
|
|
1163
|
+
status: response.status,
|
|
1164
|
+
statusText: response.statusText,
|
|
1165
|
+
headers: response.headers
|
|
1166
|
+
});
|
|
1167
|
+
streamResponse.processDataStream = async ({
|
|
1168
|
+
onChunk
|
|
1169
|
+
}) => {
|
|
1170
|
+
await processMastraStream({
|
|
1171
|
+
stream: streamResponse.body,
|
|
1172
|
+
onChunk
|
|
1173
|
+
});
|
|
1174
|
+
};
|
|
1175
|
+
return streamResponse;
|
|
1176
|
+
}
|
|
1177
|
+
async declineToolCall(params) {
|
|
1178
|
+
const { readable, writable } = new TransformStream();
|
|
1179
|
+
const response = await this.processStreamResponse(params, writable, "decline-tool-call");
|
|
1180
|
+
const streamResponse = new Response(readable, {
|
|
1181
|
+
status: response.status,
|
|
1182
|
+
statusText: response.statusText,
|
|
1183
|
+
headers: response.headers
|
|
1184
|
+
});
|
|
1185
|
+
streamResponse.processDataStream = async ({
|
|
1186
|
+
onChunk
|
|
1187
|
+
}) => {
|
|
1188
|
+
await processMastraStream({
|
|
1189
|
+
stream: streamResponse.body,
|
|
1190
|
+
onChunk
|
|
1191
|
+
});
|
|
1192
|
+
};
|
|
1193
|
+
return streamResponse;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Processes the stream response and handles tool calls
|
|
1197
|
+
*/
|
|
1198
|
+
async processStreamResponseLegacy(processedParams, writable) {
|
|
1199
|
+
const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
|
|
1200
|
+
method: "POST",
|
|
1201
|
+
body: processedParams,
|
|
1202
|
+
stream: true
|
|
1203
|
+
});
|
|
1204
|
+
if (!response.body) {
|
|
1205
|
+
throw new Error("No response body");
|
|
1206
|
+
}
|
|
1207
|
+
try {
|
|
1208
|
+
let toolCalls = [];
|
|
1209
|
+
let messages = [];
|
|
1210
|
+
const [streamForWritable, streamForProcessing] = response.body.tee();
|
|
1211
|
+
streamForWritable.pipeTo(writable, {
|
|
1212
|
+
preventClose: true
|
|
1213
|
+
}).catch((error) => {
|
|
1214
|
+
console.error("Error piping to writable stream:", error);
|
|
1215
|
+
});
|
|
1216
|
+
this.processChatResponse({
|
|
1217
|
+
stream: streamForProcessing,
|
|
1218
|
+
update: ({ message }) => {
|
|
1219
|
+
const existingIndex = messages.findIndex((m) => m.id === message.id);
|
|
1220
|
+
if (existingIndex !== -1) {
|
|
1221
|
+
messages[existingIndex] = message;
|
|
1222
|
+
} else {
|
|
1223
|
+
messages.push(message);
|
|
1224
|
+
}
|
|
1225
|
+
},
|
|
1226
|
+
onFinish: async ({ finishReason, message }) => {
|
|
1227
|
+
if (finishReason === "tool-calls") {
|
|
1228
|
+
const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
|
|
1229
|
+
if (toolCall) {
|
|
1230
|
+
toolCalls.push(toolCall);
|
|
1231
|
+
}
|
|
1232
|
+
for (const toolCall2 of toolCalls) {
|
|
1233
|
+
const clientTool = processedParams.clientTools?.[toolCall2.toolName];
|
|
1234
|
+
if (clientTool && clientTool.execute) {
|
|
1235
|
+
const result = await clientTool.execute(toolCall2?.args, {
|
|
1236
|
+
requestContext: processedParams.requestContext,
|
|
1237
|
+
// TODO: Pass proper tracing context when client-js supports tracing
|
|
1238
|
+
tracingContext: { currentSpan: void 0 },
|
|
1239
|
+
agent: {
|
|
1240
|
+
messages: response.messages,
|
|
1241
|
+
toolCallId: toolCall2?.toolCallId,
|
|
1242
|
+
suspend: async () => {
|
|
1243
|
+
},
|
|
1244
|
+
threadId: processedParams.threadId,
|
|
1245
|
+
resourceId: processedParams.resourceId
|
|
1246
|
+
}
|
|
1247
|
+
});
|
|
1248
|
+
const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
|
|
1249
|
+
const toolInvocationPart = lastMessage?.parts?.find(
|
|
1250
|
+
(part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
|
|
1251
|
+
);
|
|
1252
|
+
if (toolInvocationPart) {
|
|
1253
|
+
toolInvocationPart.toolInvocation = {
|
|
1254
|
+
...toolInvocationPart.toolInvocation,
|
|
1255
|
+
state: "result",
|
|
1256
|
+
result
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
const toolInvocation = lastMessage?.toolInvocations?.find(
|
|
1260
|
+
(toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
|
|
1261
|
+
);
|
|
1262
|
+
if (toolInvocation) {
|
|
1263
|
+
toolInvocation.state = "result";
|
|
1264
|
+
toolInvocation.result = result;
|
|
1265
|
+
}
|
|
1266
|
+
const writer = writable.getWriter();
|
|
1267
|
+
try {
|
|
1268
|
+
await writer.write(
|
|
1269
|
+
new TextEncoder().encode(
|
|
1270
|
+
"a:" + JSON.stringify({
|
|
1271
|
+
toolCallId: toolCall2.toolCallId,
|
|
1272
|
+
result
|
|
1273
|
+
}) + "\n"
|
|
1274
|
+
)
|
|
1275
|
+
);
|
|
1276
|
+
} finally {
|
|
1277
|
+
writer.releaseLock();
|
|
1278
|
+
}
|
|
1279
|
+
this.processStreamResponseLegacy(
|
|
1280
|
+
{
|
|
1281
|
+
...processedParams,
|
|
1282
|
+
messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
|
|
1283
|
+
},
|
|
1284
|
+
writable
|
|
1285
|
+
).catch((error) => {
|
|
1286
|
+
console.error("Error processing stream response:", error);
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
} else {
|
|
1291
|
+
setTimeout(() => {
|
|
1292
|
+
writable.close();
|
|
1293
|
+
}, 0);
|
|
1294
|
+
}
|
|
1295
|
+
},
|
|
1296
|
+
lastMessage: void 0
|
|
1297
|
+
}).catch((error) => {
|
|
1298
|
+
console.error("Error processing stream response:", error);
|
|
1299
|
+
});
|
|
1300
|
+
} catch (error) {
|
|
1301
|
+
console.error("Error processing stream response:", error);
|
|
1302
|
+
}
|
|
1303
|
+
return response;
|
|
1304
|
+
}
|
|
1305
|
+
/**
|
|
1306
|
+
* Gets details about a specific tool available to the agent
|
|
1307
|
+
* @param toolId - ID of the tool to retrieve
|
|
1308
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1309
|
+
* @returns Promise containing tool details
|
|
1310
|
+
*/
|
|
1311
|
+
getTool(toolId, requestContext) {
|
|
1312
|
+
return this.request(`/api/agents/${this.agentId}/tools/${toolId}${requestContextQueryString(requestContext)}`);
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* Executes a tool for the agent
|
|
1316
|
+
* @param toolId - ID of the tool to execute
|
|
1317
|
+
* @param params - Parameters required for tool execution
|
|
1318
|
+
* @returns Promise containing the tool execution results
|
|
1319
|
+
*/
|
|
1320
|
+
executeTool(toolId, params) {
|
|
1321
|
+
const body = {
|
|
1322
|
+
data: params.data,
|
|
1323
|
+
requestContext: parseClientRequestContext(params.requestContext)
|
|
1324
|
+
};
|
|
1325
|
+
return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
|
|
1326
|
+
method: "POST",
|
|
1327
|
+
body
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Updates the model for the agent
|
|
1332
|
+
* @param params - Parameters for updating the model
|
|
1333
|
+
* @returns Promise containing the updated model
|
|
1334
|
+
*/
|
|
1335
|
+
updateModel(params) {
|
|
1336
|
+
return this.request(`/api/agents/${this.agentId}/model`, {
|
|
1337
|
+
method: "POST",
|
|
1338
|
+
body: params
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Resets the agent's model to the original model that was set during construction
|
|
1343
|
+
* @returns Promise containing a success message
|
|
1344
|
+
*/
|
|
1345
|
+
resetModel() {
|
|
1346
|
+
return this.request(`/api/agents/${this.agentId}/model/reset`, {
|
|
1347
|
+
method: "POST"
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Updates the model for the agent in the model list
|
|
1352
|
+
* @param params - Parameters for updating the model
|
|
1353
|
+
* @returns Promise containing the updated model
|
|
1354
|
+
*/
|
|
1355
|
+
updateModelInModelList({ modelConfigId, ...params }) {
|
|
1356
|
+
return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
|
|
1357
|
+
method: "POST",
|
|
1358
|
+
body: params
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* Reorders the models for the agent
|
|
1363
|
+
* @param params - Parameters for reordering the model list
|
|
1364
|
+
* @returns Promise containing the updated model list
|
|
1365
|
+
*/
|
|
1366
|
+
reorderModelList(params) {
|
|
1367
|
+
return this.request(`/api/agents/${this.agentId}/models/reorder`, {
|
|
1368
|
+
method: "POST",
|
|
1369
|
+
body: params
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
// src/resources/memory-thread.ts
|
|
1375
|
+
var MemoryThread = class extends BaseResource {
|
|
1376
|
+
constructor(options, threadId, agentId) {
|
|
1377
|
+
super(options);
|
|
1378
|
+
this.threadId = threadId;
|
|
1379
|
+
this.agentId = agentId;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Retrieves the memory thread details
|
|
1383
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1384
|
+
* @returns Promise containing thread details including title and metadata
|
|
1385
|
+
*/
|
|
1386
|
+
get(requestContext) {
|
|
1387
|
+
return this.request(
|
|
1388
|
+
`/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(requestContext, "&")}`
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Updates the memory thread properties
|
|
1393
|
+
* @param params - Update parameters including title, metadata, and optional request context
|
|
1394
|
+
* @returns Promise containing updated thread details
|
|
1395
|
+
*/
|
|
1396
|
+
update(params) {
|
|
1397
|
+
return this.request(
|
|
1398
|
+
`/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(params.requestContext, "&")}`,
|
|
1399
|
+
{
|
|
1400
|
+
method: "PATCH",
|
|
1401
|
+
body: params
|
|
1402
|
+
}
|
|
1403
|
+
);
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Deletes the memory thread
|
|
1407
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1408
|
+
* @returns Promise containing deletion result
|
|
1409
|
+
*/
|
|
1410
|
+
delete(requestContext) {
|
|
1411
|
+
return this.request(
|
|
1412
|
+
`/api/memory/threads/${this.threadId}?agentId=${this.agentId}${requestContextQueryString(requestContext, "&")}`,
|
|
1413
|
+
{
|
|
1414
|
+
method: "DELETE"
|
|
1415
|
+
}
|
|
1416
|
+
);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Retrieves paginated messages associated with the thread with filtering and ordering options
|
|
1420
|
+
* @param params - Pagination parameters including page, perPage, orderBy, filter, include options, and request context
|
|
1421
|
+
* @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
|
|
1422
|
+
*/
|
|
1423
|
+
listMessages(params = {}) {
|
|
1424
|
+
const { page, perPage, orderBy, filter, include, resourceId, requestContext } = params;
|
|
1425
|
+
const queryParams = {};
|
|
1426
|
+
if (resourceId) queryParams.resourceId = resourceId;
|
|
1427
|
+
if (page !== void 0) queryParams.page = String(page);
|
|
1428
|
+
if (perPage !== void 0) queryParams.perPage = String(perPage);
|
|
1429
|
+
if (orderBy) queryParams.orderBy = JSON.stringify(orderBy);
|
|
1430
|
+
if (filter) queryParams.filter = JSON.stringify(filter);
|
|
1431
|
+
if (include) queryParams.include = JSON.stringify(include);
|
|
1432
|
+
const query = new URLSearchParams(queryParams);
|
|
1433
|
+
const queryString = query.toString();
|
|
1434
|
+
const url = `/api/memory/threads/${this.threadId}/messages${queryString ? `?${queryString}` : ""}${requestContextQueryString(requestContext, queryString ? "&" : "?")}`;
|
|
1435
|
+
return this.request(url);
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Deletes one or more messages from the thread
|
|
1439
|
+
* @param messageIds - Can be a single message ID (string), array of message IDs,
|
|
1440
|
+
* message object with id property, or array of message objects
|
|
1441
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1442
|
+
* @returns Promise containing deletion result
|
|
1443
|
+
*/
|
|
1444
|
+
deleteMessages(messageIds, requestContext) {
|
|
1445
|
+
const query = new URLSearchParams({
|
|
1446
|
+
agentId: this.agentId
|
|
1447
|
+
});
|
|
1448
|
+
return this.request(
|
|
1449
|
+
`/api/memory/messages/delete?${query.toString()}${requestContextQueryString(requestContext, "&")}`,
|
|
1450
|
+
{
|
|
1451
|
+
method: "POST",
|
|
1452
|
+
body: { messageIds }
|
|
1453
|
+
}
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
|
|
1458
|
+
// src/resources/vector.ts
|
|
1459
|
+
var Vector = class extends BaseResource {
|
|
1460
|
+
constructor(options, vectorName) {
|
|
1461
|
+
super(options);
|
|
1462
|
+
this.vectorName = vectorName;
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Retrieves details about a specific vector index
|
|
1466
|
+
* @param indexName - Name of the index to get details for
|
|
1467
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1468
|
+
* @returns Promise containing vector index details
|
|
1469
|
+
*/
|
|
1470
|
+
details(indexName, requestContext) {
|
|
1471
|
+
return this.request(
|
|
1472
|
+
`/api/vector/${this.vectorName}/indexes/${indexName}${requestContextQueryString(requestContext)}`
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* Deletes a vector index
|
|
1477
|
+
* @param indexName - Name of the index to delete
|
|
1478
|
+
* @returns Promise indicating deletion success
|
|
1479
|
+
*/
|
|
1480
|
+
delete(indexName) {
|
|
1481
|
+
return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`, {
|
|
1482
|
+
method: "DELETE"
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Retrieves a list of all available indexes
|
|
1487
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1488
|
+
* @returns Promise containing array of index names
|
|
1489
|
+
*/
|
|
1490
|
+
getIndexes(requestContext) {
|
|
1491
|
+
return this.request(`/api/vector/${this.vectorName}/indexes${requestContextQueryString(requestContext)}`);
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Creates a new vector index
|
|
1495
|
+
* @param params - Parameters for index creation including dimension and metric
|
|
1496
|
+
* @returns Promise indicating creation success
|
|
1497
|
+
*/
|
|
1498
|
+
createIndex(params) {
|
|
1499
|
+
return this.request(`/api/vector/${this.vectorName}/create-index`, {
|
|
1500
|
+
method: "POST",
|
|
1501
|
+
body: params
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Upserts vectors into an index
|
|
1506
|
+
* @param params - Parameters containing vectors, metadata, and optional IDs
|
|
1507
|
+
* @returns Promise containing array of vector IDs
|
|
1508
|
+
*/
|
|
1509
|
+
upsert(params) {
|
|
1510
|
+
return this.request(`/api/vector/${this.vectorName}/upsert`, {
|
|
1511
|
+
method: "POST",
|
|
1512
|
+
body: params
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Queries vectors in an index
|
|
1517
|
+
* @param params - Query parameters including query vector and search options
|
|
1518
|
+
* @returns Promise containing query results
|
|
1519
|
+
*/
|
|
1520
|
+
query(params) {
|
|
1521
|
+
return this.request(`/api/vector/${this.vectorName}/query`, {
|
|
1522
|
+
method: "POST",
|
|
1523
|
+
body: params
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
// src/resources/tool.ts
|
|
1529
|
+
var Tool = class extends BaseResource {
|
|
1530
|
+
constructor(options, toolId) {
|
|
1531
|
+
super(options);
|
|
1532
|
+
this.toolId = toolId;
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Retrieves details about the tool
|
|
1536
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1537
|
+
* @returns Promise containing tool details including description and schemas
|
|
1538
|
+
*/
|
|
1539
|
+
details(requestContext) {
|
|
1540
|
+
return this.request(`/api/tools/${this.toolId}${requestContextQueryString(requestContext)}`);
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* Executes the tool with the provided parameters
|
|
1544
|
+
* @param params - Parameters required for tool execution
|
|
1545
|
+
* @returns Promise containing the tool execution results
|
|
1546
|
+
*/
|
|
1547
|
+
execute(params) {
|
|
1548
|
+
const url = new URLSearchParams();
|
|
1549
|
+
if (params.runId) {
|
|
1550
|
+
url.set("runId", params.runId);
|
|
1551
|
+
}
|
|
1552
|
+
const body = {
|
|
1553
|
+
data: params.data,
|
|
1554
|
+
requestContext: parseClientRequestContext(params.requestContext)
|
|
1555
|
+
};
|
|
1556
|
+
return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
|
|
1557
|
+
method: "POST",
|
|
1558
|
+
body
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
|
|
1563
|
+
// src/resources/workflow.ts
|
|
1564
|
+
var RECORD_SEPARATOR = "";
|
|
1565
|
+
var Workflow = class extends BaseResource {
|
|
1566
|
+
constructor(options, workflowId) {
|
|
1567
|
+
super(options);
|
|
1568
|
+
this.workflowId = workflowId;
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Retrieves details about the workflow
|
|
1572
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1573
|
+
* @returns Promise containing workflow details including steps and graphs
|
|
1574
|
+
*/
|
|
1575
|
+
details(requestContext) {
|
|
1576
|
+
return this.request(`/api/workflows/${this.workflowId}${requestContextQueryString(requestContext)}`);
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Retrieves all runs for a workflow
|
|
1580
|
+
* @param params - Parameters for filtering runs
|
|
1581
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1582
|
+
* @returns Promise containing workflow runs array
|
|
1583
|
+
*/
|
|
1584
|
+
runs(params, requestContext) {
|
|
1585
|
+
const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
|
|
1586
|
+
const searchParams = new URLSearchParams();
|
|
1587
|
+
if (params?.fromDate) {
|
|
1588
|
+
searchParams.set("fromDate", params.fromDate.toISOString());
|
|
1589
|
+
}
|
|
1590
|
+
if (params?.toDate) {
|
|
1591
|
+
searchParams.set("toDate", params.toDate.toISOString());
|
|
1592
|
+
}
|
|
1593
|
+
if (params?.perPage !== null && params?.perPage !== void 0) {
|
|
1594
|
+
if (params.perPage === false) {
|
|
1595
|
+
searchParams.set("perPage", "false");
|
|
1596
|
+
} else if (typeof params.perPage === "number" && params.perPage > 0 && Number.isInteger(params.perPage)) {
|
|
1597
|
+
searchParams.set("perPage", String(params.perPage));
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
if (params?.page !== null && params?.page !== void 0 && !isNaN(Number(params?.page))) {
|
|
1601
|
+
searchParams.set("page", String(params.page));
|
|
1602
|
+
}
|
|
1603
|
+
if (params?.resourceId) {
|
|
1604
|
+
searchParams.set("resourceId", params.resourceId);
|
|
1605
|
+
}
|
|
1606
|
+
if (requestContextParam) {
|
|
1607
|
+
searchParams.set("requestContext", requestContextParam);
|
|
1608
|
+
}
|
|
1609
|
+
if (searchParams.size) {
|
|
1610
|
+
return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
|
|
1611
|
+
} else {
|
|
1612
|
+
return this.request(`/api/workflows/${this.workflowId}/runs`);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* Retrieves a specific workflow run by its ID
|
|
1617
|
+
* @param runId - The ID of the workflow run to retrieve
|
|
1618
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1619
|
+
* @returns Promise containing the workflow run details
|
|
1620
|
+
*/
|
|
1621
|
+
runById(runId, requestContext) {
|
|
1622
|
+
return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${requestContextQueryString(requestContext)}`);
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Retrieves the execution result for a specific workflow run by its ID
|
|
1626
|
+
* @param runId - The ID of the workflow run to retrieve the execution result for
|
|
1627
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
1628
|
+
* @returns Promise containing the workflow run execution result
|
|
1629
|
+
*/
|
|
1630
|
+
runExecutionResult(runId, requestContext) {
|
|
1631
|
+
return this.request(
|
|
1632
|
+
`/api/workflows/${this.workflowId}/runs/${runId}/execution-result${requestContextQueryString(requestContext)}`
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Cancels a specific workflow run by its ID
|
|
1637
|
+
* @param runId - The ID of the workflow run to cancel
|
|
1638
|
+
* @returns Promise containing a success message
|
|
1639
|
+
*/
|
|
1640
|
+
cancelRun(runId) {
|
|
1641
|
+
return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
|
|
1642
|
+
method: "POST"
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
/**
|
|
1646
|
+
* Creates a new workflow run
|
|
1647
|
+
* @param params - Optional object containing the optional runId
|
|
1648
|
+
* @returns Promise containing the runId of the created run with methods to control execution
|
|
1649
|
+
*/
|
|
1650
|
+
async createRun(params) {
|
|
1651
|
+
const searchParams = new URLSearchParams();
|
|
1652
|
+
if (!!params?.runId) {
|
|
1653
|
+
searchParams.set("runId", params.runId);
|
|
1654
|
+
}
|
|
1655
|
+
const res = await this.request(
|
|
1656
|
+
`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
|
|
1657
|
+
{
|
|
1658
|
+
method: "POST"
|
|
1659
|
+
}
|
|
1660
|
+
);
|
|
1661
|
+
const runId = res.runId;
|
|
1662
|
+
return {
|
|
1663
|
+
runId,
|
|
1664
|
+
start: async (p) => {
|
|
1665
|
+
return this.start({
|
|
1666
|
+
runId,
|
|
1667
|
+
inputData: p.inputData,
|
|
1668
|
+
requestContext: p.requestContext,
|
|
1669
|
+
tracingOptions: p.tracingOptions
|
|
1670
|
+
});
|
|
1671
|
+
},
|
|
1672
|
+
startAsync: async (p) => {
|
|
1673
|
+
return this.startAsync({
|
|
1674
|
+
runId,
|
|
1675
|
+
inputData: p.inputData,
|
|
1676
|
+
requestContext: p.requestContext,
|
|
1677
|
+
tracingOptions: p.tracingOptions
|
|
1678
|
+
});
|
|
1679
|
+
},
|
|
1680
|
+
stream: async (p) => {
|
|
1681
|
+
return this.stream({ runId, inputData: p.inputData, requestContext: p.requestContext });
|
|
1682
|
+
},
|
|
1683
|
+
resume: async (p) => {
|
|
1684
|
+
return this.resume({
|
|
1685
|
+
runId,
|
|
1686
|
+
step: p.step,
|
|
1687
|
+
resumeData: p.resumeData,
|
|
1688
|
+
requestContext: p.requestContext,
|
|
1689
|
+
tracingOptions: p.tracingOptions
|
|
1690
|
+
});
|
|
1691
|
+
},
|
|
1692
|
+
resumeAsync: async (p) => {
|
|
1693
|
+
return this.resumeAsync({
|
|
1694
|
+
runId,
|
|
1695
|
+
step: p.step,
|
|
1696
|
+
resumeData: p.resumeData,
|
|
1697
|
+
requestContext: p.requestContext,
|
|
1698
|
+
tracingOptions: p.tracingOptions
|
|
1699
|
+
});
|
|
1700
|
+
},
|
|
1701
|
+
resumeStreamVNext: async (p) => {
|
|
1702
|
+
return this.resumeStreamVNext({
|
|
1703
|
+
runId,
|
|
1704
|
+
step: p.step,
|
|
1705
|
+
resumeData: p.resumeData,
|
|
1706
|
+
requestContext: p.requestContext
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Starts a workflow run synchronously without waiting for the workflow to complete
|
|
1713
|
+
* @param params - Object containing the runId, inputData and requestContext
|
|
1714
|
+
* @returns Promise containing success message
|
|
1715
|
+
*/
|
|
1716
|
+
start(params) {
|
|
1717
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1718
|
+
return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
|
|
1719
|
+
method: "POST",
|
|
1720
|
+
body: { inputData: params?.inputData, requestContext, tracingOptions: params.tracingOptions }
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Resumes a suspended workflow step synchronously without waiting for the workflow to complete
|
|
1725
|
+
* @param params - Object containing the runId, step, resumeData and requestContext
|
|
1726
|
+
* @returns Promise containing success message
|
|
1727
|
+
*/
|
|
1728
|
+
resume({
|
|
1729
|
+
step,
|
|
1730
|
+
runId,
|
|
1731
|
+
resumeData,
|
|
1732
|
+
tracingOptions,
|
|
1733
|
+
...rest
|
|
1734
|
+
}) {
|
|
1735
|
+
const requestContext = parseClientRequestContext(rest.requestContext);
|
|
1736
|
+
return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
|
|
1737
|
+
method: "POST",
|
|
1738
|
+
body: {
|
|
1739
|
+
step,
|
|
1740
|
+
resumeData,
|
|
1741
|
+
requestContext,
|
|
1742
|
+
tracingOptions
|
|
1743
|
+
}
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
|
|
1748
|
+
* @param params - Object containing the optional runId, inputData and requestContext
|
|
1749
|
+
* @returns Promise containing the workflow execution results
|
|
1750
|
+
*/
|
|
1751
|
+
startAsync(params) {
|
|
1752
|
+
const searchParams = new URLSearchParams();
|
|
1753
|
+
if (!!params?.runId) {
|
|
1754
|
+
searchParams.set("runId", params.runId);
|
|
1755
|
+
}
|
|
1756
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1757
|
+
return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
|
|
1758
|
+
method: "POST",
|
|
1759
|
+
body: { inputData: params.inputData, requestContext, tracingOptions: params.tracingOptions }
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Starts a workflow run and returns a stream
|
|
1764
|
+
* @param params - Object containing the optional runId, inputData and requestContext
|
|
1765
|
+
* @returns Promise containing the workflow execution results
|
|
1766
|
+
*/
|
|
1767
|
+
async stream(params) {
|
|
1768
|
+
const searchParams = new URLSearchParams();
|
|
1769
|
+
if (!!params?.runId) {
|
|
1770
|
+
searchParams.set("runId", params.runId);
|
|
1771
|
+
}
|
|
1772
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1773
|
+
const response = await this.request(
|
|
1774
|
+
`/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
|
|
1775
|
+
{
|
|
1776
|
+
method: "POST",
|
|
1777
|
+
body: { inputData: params.inputData, requestContext, tracingOptions: params.tracingOptions },
|
|
1778
|
+
stream: true
|
|
1779
|
+
}
|
|
1780
|
+
);
|
|
1781
|
+
if (!response.ok) {
|
|
1782
|
+
throw new Error(`Failed to stream workflow: ${response.statusText}`);
|
|
1783
|
+
}
|
|
1784
|
+
if (!response.body) {
|
|
1785
|
+
throw new Error("Response body is null");
|
|
1786
|
+
}
|
|
1787
|
+
let failedChunk = void 0;
|
|
1788
|
+
const transformStream = new TransformStream({
|
|
1789
|
+
start() {
|
|
1790
|
+
},
|
|
1791
|
+
async transform(chunk, controller) {
|
|
1792
|
+
try {
|
|
1793
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
1794
|
+
const chunks = decoded.split(RECORD_SEPARATOR);
|
|
1795
|
+
for (const chunk2 of chunks) {
|
|
1796
|
+
if (chunk2) {
|
|
1797
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
1798
|
+
try {
|
|
1799
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
1800
|
+
controller.enqueue(parsedChunk);
|
|
1801
|
+
failedChunk = void 0;
|
|
1802
|
+
} catch {
|
|
1803
|
+
failedChunk = newChunk;
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
} catch {
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
});
|
|
1811
|
+
return response.body.pipeThrough(transformStream);
|
|
1812
|
+
}
|
|
1813
|
+
/**
|
|
1814
|
+
* Observes workflow stream for a workflow run
|
|
1815
|
+
* @param params - Object containing the runId
|
|
1816
|
+
* @returns Promise containing the workflow execution results
|
|
1817
|
+
*/
|
|
1818
|
+
async observeStream(params) {
|
|
1819
|
+
const searchParams = new URLSearchParams();
|
|
1820
|
+
searchParams.set("runId", params.runId);
|
|
1821
|
+
const response = await this.request(
|
|
1822
|
+
`/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
|
|
1823
|
+
{
|
|
1824
|
+
method: "POST",
|
|
1825
|
+
stream: true
|
|
1826
|
+
}
|
|
1827
|
+
);
|
|
1828
|
+
if (!response.ok) {
|
|
1829
|
+
throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
|
|
1830
|
+
}
|
|
1831
|
+
if (!response.body) {
|
|
1832
|
+
throw new Error("Response body is null");
|
|
1833
|
+
}
|
|
1834
|
+
let failedChunk = void 0;
|
|
1835
|
+
const transformStream = new TransformStream({
|
|
1836
|
+
start() {
|
|
1837
|
+
},
|
|
1838
|
+
async transform(chunk, controller) {
|
|
1839
|
+
try {
|
|
1840
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
1841
|
+
const chunks = decoded.split(RECORD_SEPARATOR);
|
|
1842
|
+
for (const chunk2 of chunks) {
|
|
1843
|
+
if (chunk2) {
|
|
1844
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
1845
|
+
try {
|
|
1846
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
1847
|
+
controller.enqueue(parsedChunk);
|
|
1848
|
+
failedChunk = void 0;
|
|
1849
|
+
} catch {
|
|
1850
|
+
failedChunk = newChunk;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
} catch {
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
return response.body.pipeThrough(transformStream);
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Starts a workflow run and returns a stream
|
|
1862
|
+
* @param params - Object containing the optional runId, inputData and requestContext
|
|
1863
|
+
* @returns Promise containing the workflow execution results
|
|
1864
|
+
*/
|
|
1865
|
+
async streamVNext(params) {
|
|
1866
|
+
const searchParams = new URLSearchParams();
|
|
1867
|
+
if (!!params?.runId) {
|
|
1868
|
+
searchParams.set("runId", params.runId);
|
|
1869
|
+
}
|
|
1870
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1871
|
+
const response = await this.request(
|
|
1872
|
+
`/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
|
|
1873
|
+
{
|
|
1874
|
+
method: "POST",
|
|
1875
|
+
body: {
|
|
1876
|
+
inputData: params.inputData,
|
|
1877
|
+
requestContext,
|
|
1878
|
+
closeOnSuspend: params.closeOnSuspend,
|
|
1879
|
+
tracingOptions: params.tracingOptions
|
|
1880
|
+
},
|
|
1881
|
+
stream: true
|
|
1882
|
+
}
|
|
1883
|
+
);
|
|
1884
|
+
if (!response.ok) {
|
|
1885
|
+
throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
|
|
1886
|
+
}
|
|
1887
|
+
if (!response.body) {
|
|
1888
|
+
throw new Error("Response body is null");
|
|
1889
|
+
}
|
|
1890
|
+
let failedChunk = void 0;
|
|
1891
|
+
const transformStream = new TransformStream({
|
|
1892
|
+
start() {
|
|
1893
|
+
},
|
|
1894
|
+
async transform(chunk, controller) {
|
|
1895
|
+
try {
|
|
1896
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
1897
|
+
const chunks = decoded.split(RECORD_SEPARATOR);
|
|
1898
|
+
for (const chunk2 of chunks) {
|
|
1899
|
+
if (chunk2) {
|
|
1900
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
1901
|
+
try {
|
|
1902
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
1903
|
+
controller.enqueue(parsedChunk);
|
|
1904
|
+
failedChunk = void 0;
|
|
1905
|
+
} catch {
|
|
1906
|
+
failedChunk = newChunk;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
} catch {
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
return response.body.pipeThrough(transformStream);
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* Observes workflow vNext stream for a workflow run
|
|
1918
|
+
* @param params - Object containing the runId
|
|
1919
|
+
* @returns Promise containing the workflow execution results
|
|
1920
|
+
*/
|
|
1921
|
+
async observeStreamVNext(params) {
|
|
1922
|
+
const searchParams = new URLSearchParams();
|
|
1923
|
+
searchParams.set("runId", params.runId);
|
|
1924
|
+
const response = await this.request(
|
|
1925
|
+
`/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
|
|
1926
|
+
{
|
|
1927
|
+
method: "POST",
|
|
1928
|
+
stream: true
|
|
1929
|
+
}
|
|
1930
|
+
);
|
|
1931
|
+
if (!response.ok) {
|
|
1932
|
+
throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
|
|
1933
|
+
}
|
|
1934
|
+
if (!response.body) {
|
|
1935
|
+
throw new Error("Response body is null");
|
|
1936
|
+
}
|
|
1937
|
+
let failedChunk = void 0;
|
|
1938
|
+
const transformStream = new TransformStream({
|
|
1939
|
+
start() {
|
|
1940
|
+
},
|
|
1941
|
+
async transform(chunk, controller) {
|
|
1942
|
+
try {
|
|
1943
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
1944
|
+
const chunks = decoded.split(RECORD_SEPARATOR);
|
|
1945
|
+
for (const chunk2 of chunks) {
|
|
1946
|
+
if (chunk2) {
|
|
1947
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
1948
|
+
try {
|
|
1949
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
1950
|
+
controller.enqueue(parsedChunk);
|
|
1951
|
+
failedChunk = void 0;
|
|
1952
|
+
} catch {
|
|
1953
|
+
failedChunk = newChunk;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
} catch {
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
return response.body.pipeThrough(transformStream);
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
|
|
1965
|
+
* @param params - Object containing the runId, step, resumeData and requestContext
|
|
1966
|
+
* @returns Promise containing the workflow resume results
|
|
1967
|
+
*/
|
|
1968
|
+
resumeAsync(params) {
|
|
1969
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1970
|
+
return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
|
|
1971
|
+
method: "POST",
|
|
1972
|
+
body: {
|
|
1973
|
+
step: params.step,
|
|
1974
|
+
resumeData: params.resumeData,
|
|
1975
|
+
requestContext,
|
|
1976
|
+
tracingOptions: params.tracingOptions
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
|
|
1982
|
+
* @param params - Object containing the runId, step, resumeData and requestContext
|
|
1983
|
+
* @returns Promise containing the workflow resume results
|
|
1984
|
+
*/
|
|
1985
|
+
async resumeStreamVNext(params) {
|
|
1986
|
+
const searchParams = new URLSearchParams();
|
|
1987
|
+
searchParams.set("runId", params.runId);
|
|
1988
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
1989
|
+
const response = await this.request(
|
|
1990
|
+
`/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
|
|
1991
|
+
{
|
|
1992
|
+
method: "POST",
|
|
1993
|
+
body: {
|
|
1994
|
+
step: params.step,
|
|
1995
|
+
resumeData: params.resumeData,
|
|
1996
|
+
requestContext,
|
|
1997
|
+
tracingOptions: params.tracingOptions
|
|
1998
|
+
},
|
|
1999
|
+
stream: true
|
|
2000
|
+
}
|
|
2001
|
+
);
|
|
2002
|
+
if (!response.ok) {
|
|
2003
|
+
throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
|
|
2004
|
+
}
|
|
2005
|
+
if (!response.body) {
|
|
2006
|
+
throw new Error("Response body is null");
|
|
2007
|
+
}
|
|
2008
|
+
let failedChunk = void 0;
|
|
2009
|
+
const transformStream = new TransformStream({
|
|
2010
|
+
start() {
|
|
2011
|
+
},
|
|
2012
|
+
async transform(chunk, controller) {
|
|
2013
|
+
try {
|
|
2014
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
2015
|
+
const chunks = decoded.split(RECORD_SEPARATOR);
|
|
2016
|
+
for (const chunk2 of chunks) {
|
|
2017
|
+
if (chunk2) {
|
|
2018
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
2019
|
+
try {
|
|
2020
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
2021
|
+
controller.enqueue(parsedChunk);
|
|
2022
|
+
failedChunk = void 0;
|
|
2023
|
+
} catch {
|
|
2024
|
+
failedChunk = newChunk;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
} catch {
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
});
|
|
2032
|
+
return response.body.pipeThrough(transformStream);
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* Creates a new ReadableStream from an iterable or async iterable of objects,
|
|
2036
|
+
* serializing each as JSON and separating them with the record separator (\x1E).
|
|
2037
|
+
*
|
|
2038
|
+
* @param records - An iterable or async iterable of objects to stream
|
|
2039
|
+
* @returns A ReadableStream emitting the records as JSON strings separated by the record separator
|
|
2040
|
+
*/
|
|
2041
|
+
static createRecordStream(records) {
|
|
2042
|
+
const encoder = new TextEncoder();
|
|
2043
|
+
return new ReadableStream({
|
|
2044
|
+
async start(controller) {
|
|
2045
|
+
try {
|
|
2046
|
+
for await (const record of records) {
|
|
2047
|
+
const json = JSON.stringify(record) + RECORD_SEPARATOR;
|
|
2048
|
+
controller.enqueue(encoder.encode(json));
|
|
2049
|
+
}
|
|
2050
|
+
controller.close();
|
|
2051
|
+
} catch (err) {
|
|
2052
|
+
controller.error(err);
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
};
|
|
2058
|
+
|
|
2059
|
+
// src/resources/a2a.ts
|
|
2060
|
+
var A2A = class extends BaseResource {
|
|
2061
|
+
constructor(options, agentId) {
|
|
2062
|
+
super(options);
|
|
2063
|
+
this.agentId = agentId;
|
|
2064
|
+
}
|
|
2065
|
+
/**
|
|
2066
|
+
* Get the agent card with metadata about the agent
|
|
2067
|
+
* @returns Promise containing the agent card information
|
|
2068
|
+
*/
|
|
2069
|
+
async getCard() {
|
|
2070
|
+
return this.request(`/.well-known/${this.agentId}/agent-card.json`);
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* Send a message to the agent and gets a message or task response
|
|
2074
|
+
* @param params - Parameters for the task
|
|
2075
|
+
* @returns Promise containing the response
|
|
2076
|
+
*/
|
|
2077
|
+
async sendMessage(params) {
|
|
2078
|
+
const response = await this.request(`/a2a/${this.agentId}`, {
|
|
2079
|
+
method: "POST",
|
|
2080
|
+
body: {
|
|
2081
|
+
method: "message/send",
|
|
2082
|
+
params
|
|
2083
|
+
}
|
|
2084
|
+
});
|
|
2085
|
+
return response;
|
|
2086
|
+
}
|
|
2087
|
+
/**
|
|
2088
|
+
* Sends a message to an agent to initiate/continue a task and subscribes
|
|
2089
|
+
* the client to real-time updates for that task via Server-Sent Events (SSE).
|
|
2090
|
+
* @param params - Parameters for the task
|
|
2091
|
+
* @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
|
|
2092
|
+
*/
|
|
2093
|
+
async sendStreamingMessage(params) {
|
|
2094
|
+
const response = await this.request(`/a2a/${this.agentId}`, {
|
|
2095
|
+
method: "POST",
|
|
2096
|
+
body: {
|
|
2097
|
+
method: "message/stream",
|
|
2098
|
+
params
|
|
2099
|
+
}
|
|
2100
|
+
});
|
|
2101
|
+
return response;
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* Get the status and result of a task
|
|
2105
|
+
* @param params - Parameters for querying the task
|
|
2106
|
+
* @returns Promise containing the task response
|
|
2107
|
+
*/
|
|
2108
|
+
async getTask(params) {
|
|
2109
|
+
const response = await this.request(`/a2a/${this.agentId}`, {
|
|
2110
|
+
method: "POST",
|
|
2111
|
+
body: {
|
|
2112
|
+
method: "tasks/get",
|
|
2113
|
+
params
|
|
2114
|
+
}
|
|
2115
|
+
});
|
|
2116
|
+
return response;
|
|
2117
|
+
}
|
|
2118
|
+
/**
|
|
2119
|
+
* Cancel a running task
|
|
2120
|
+
* @param params - Parameters identifying the task to cancel
|
|
2121
|
+
* @returns Promise containing the task response
|
|
2122
|
+
*/
|
|
2123
|
+
async cancelTask(params) {
|
|
2124
|
+
return this.request(`/a2a/${this.agentId}`, {
|
|
2125
|
+
method: "POST",
|
|
2126
|
+
body: {
|
|
2127
|
+
method: "tasks/cancel",
|
|
2128
|
+
params
|
|
2129
|
+
}
|
|
2130
|
+
});
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
|
|
2134
|
+
// src/resources/mcp-tool.ts
|
|
2135
|
+
var MCPTool = class extends BaseResource {
|
|
2136
|
+
serverId;
|
|
2137
|
+
toolId;
|
|
2138
|
+
constructor(options, serverId, toolId) {
|
|
2139
|
+
super(options);
|
|
2140
|
+
this.serverId = serverId;
|
|
2141
|
+
this.toolId = toolId;
|
|
2142
|
+
}
|
|
2143
|
+
/**
|
|
2144
|
+
* Retrieves details about this specific tool from the MCP server.
|
|
2145
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
2146
|
+
* @returns Promise containing the tool's information (name, description, schema).
|
|
2147
|
+
*/
|
|
2148
|
+
details(requestContext) {
|
|
2149
|
+
return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${requestContextQueryString(requestContext)}`);
|
|
2150
|
+
}
|
|
2151
|
+
/**
|
|
2152
|
+
* Executes this specific tool on the MCP server.
|
|
2153
|
+
* @param params - Parameters for tool execution, including data/args and optional requestContext.
|
|
2154
|
+
* @returns Promise containing the result of the tool execution.
|
|
2155
|
+
*/
|
|
2156
|
+
execute(params) {
|
|
2157
|
+
const body = {};
|
|
2158
|
+
if (params.data !== void 0) body.data = params.data;
|
|
2159
|
+
if (params.requestContext !== void 0) {
|
|
2160
|
+
body.requestContext = params.requestContext;
|
|
2161
|
+
}
|
|
2162
|
+
return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
|
|
2163
|
+
method: "POST",
|
|
2164
|
+
body: Object.keys(body).length > 0 ? body : void 0
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
|
|
2169
|
+
// src/resources/agent-builder.ts
|
|
2170
|
+
var RECORD_SEPARATOR2 = "";
|
|
2171
|
+
var AgentBuilder = class extends BaseResource {
|
|
2172
|
+
constructor(options, actionId) {
|
|
2173
|
+
super(options);
|
|
2174
|
+
this.actionId = actionId;
|
|
2175
|
+
}
|
|
2176
|
+
// Helper function to transform workflow result to action result
|
|
2177
|
+
transformWorkflowResult(result) {
|
|
2178
|
+
if (result.status === "success") {
|
|
2179
|
+
return {
|
|
2180
|
+
success: result.result.success || false,
|
|
2181
|
+
applied: result.result.applied || false,
|
|
2182
|
+
branchName: result.result.branchName,
|
|
2183
|
+
message: result.result.message || "Agent builder action completed",
|
|
2184
|
+
validationResults: result.result.validationResults,
|
|
2185
|
+
error: result.result.error,
|
|
2186
|
+
errors: result.result.errors,
|
|
2187
|
+
stepResults: result.result.stepResults
|
|
2188
|
+
};
|
|
2189
|
+
} else if (result.status === "failed") {
|
|
2190
|
+
return {
|
|
2191
|
+
success: false,
|
|
2192
|
+
applied: false,
|
|
2193
|
+
message: `Agent builder action failed: ${result.error.message}`,
|
|
2194
|
+
error: result.error.message
|
|
2195
|
+
};
|
|
2196
|
+
} else {
|
|
2197
|
+
return {
|
|
2198
|
+
success: false,
|
|
2199
|
+
applied: false,
|
|
2200
|
+
message: "Agent builder action was suspended",
|
|
2201
|
+
error: "Workflow suspended - manual intervention required"
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
/**
|
|
2206
|
+
* Creates a transform stream that parses binary chunks into JSON records.
|
|
2207
|
+
*/
|
|
2208
|
+
createRecordParserTransform() {
|
|
2209
|
+
let failedChunk = void 0;
|
|
2210
|
+
return new TransformStream({
|
|
2211
|
+
start() {
|
|
2212
|
+
},
|
|
2213
|
+
async transform(chunk, controller) {
|
|
2214
|
+
try {
|
|
2215
|
+
const decoded = new TextDecoder().decode(chunk);
|
|
2216
|
+
const chunks = decoded.split(RECORD_SEPARATOR2);
|
|
2217
|
+
for (const chunk2 of chunks) {
|
|
2218
|
+
if (chunk2) {
|
|
2219
|
+
const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
|
|
2220
|
+
try {
|
|
2221
|
+
const parsedChunk = JSON.parse(newChunk);
|
|
2222
|
+
controller.enqueue(parsedChunk);
|
|
2223
|
+
failedChunk = void 0;
|
|
2224
|
+
} catch {
|
|
2225
|
+
failedChunk = newChunk;
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
} catch {
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
/**
|
|
2235
|
+
* Creates a new agent builder action run and returns the runId.
|
|
2236
|
+
* This calls `/api/agent-builder/:actionId/create-run`.
|
|
2237
|
+
*/
|
|
2238
|
+
async createRun(params) {
|
|
2239
|
+
const searchParams = new URLSearchParams();
|
|
2240
|
+
if (!!params?.runId) {
|
|
2241
|
+
searchParams.set("runId", params.runId);
|
|
2242
|
+
}
|
|
2243
|
+
const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
2244
|
+
return this.request(url, {
|
|
2245
|
+
method: "POST"
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Starts agent builder action asynchronously and waits for completion.
|
|
2250
|
+
* This calls `/api/agent-builder/:actionId/start-async`.
|
|
2251
|
+
*/
|
|
2252
|
+
async startAsync(params, runId) {
|
|
2253
|
+
const searchParams = new URLSearchParams();
|
|
2254
|
+
if (runId) {
|
|
2255
|
+
searchParams.set("runId", runId);
|
|
2256
|
+
}
|
|
2257
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2258
|
+
const { requestContext: _, ...actionParams } = params;
|
|
2259
|
+
const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
2260
|
+
const result = await this.request(url, {
|
|
2261
|
+
method: "POST",
|
|
2262
|
+
body: { ...actionParams, requestContext }
|
|
2263
|
+
});
|
|
2264
|
+
return this.transformWorkflowResult(result);
|
|
2265
|
+
}
|
|
2266
|
+
/**
|
|
2267
|
+
* Starts an existing agent builder action run.
|
|
2268
|
+
* This calls `/api/agent-builder/:actionId/start`.
|
|
2269
|
+
*/
|
|
2270
|
+
async startActionRun(params, runId) {
|
|
2271
|
+
const searchParams = new URLSearchParams();
|
|
2272
|
+
searchParams.set("runId", runId);
|
|
2273
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2274
|
+
const { requestContext: _, ...actionParams } = params;
|
|
2275
|
+
const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
|
|
2276
|
+
return this.request(url, {
|
|
2277
|
+
method: "POST",
|
|
2278
|
+
body: { ...actionParams, requestContext }
|
|
2279
|
+
});
|
|
2280
|
+
}
|
|
2281
|
+
/**
|
|
2282
|
+
* Resumes a suspended agent builder action step.
|
|
2283
|
+
* This calls `/api/agent-builder/:actionId/resume`.
|
|
2284
|
+
*/
|
|
2285
|
+
async resume(params, runId) {
|
|
2286
|
+
const searchParams = new URLSearchParams();
|
|
2287
|
+
searchParams.set("runId", runId);
|
|
2288
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2289
|
+
const { requestContext: _, ...resumeParams } = params;
|
|
2290
|
+
const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
|
|
2291
|
+
return this.request(url, {
|
|
2292
|
+
method: "POST",
|
|
2293
|
+
body: { ...resumeParams, requestContext }
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
/**
|
|
2297
|
+
* Resumes a suspended agent builder action step asynchronously.
|
|
2298
|
+
* This calls `/api/agent-builder/:actionId/resume-async`.
|
|
2299
|
+
*/
|
|
2300
|
+
async resumeAsync(params, runId) {
|
|
2301
|
+
const searchParams = new URLSearchParams();
|
|
2302
|
+
searchParams.set("runId", runId);
|
|
2303
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2304
|
+
const { requestContext: _, ...resumeParams } = params;
|
|
2305
|
+
const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
|
|
2306
|
+
const result = await this.request(url, {
|
|
2307
|
+
method: "POST",
|
|
2308
|
+
body: { ...resumeParams, requestContext }
|
|
2309
|
+
});
|
|
2310
|
+
return this.transformWorkflowResult(result);
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Creates an async generator that processes a readable stream and yields action records
|
|
2314
|
+
* separated by the Record Separator character (\x1E)
|
|
2315
|
+
*
|
|
2316
|
+
* @param stream - The readable stream to process
|
|
2317
|
+
* @returns An async generator that yields parsed records
|
|
2318
|
+
*/
|
|
2319
|
+
async *streamProcessor(stream) {
|
|
2320
|
+
const reader = stream.getReader();
|
|
2321
|
+
let doneReading = false;
|
|
2322
|
+
let buffer = "";
|
|
2323
|
+
try {
|
|
2324
|
+
while (!doneReading) {
|
|
2325
|
+
const { done, value } = await reader.read();
|
|
2326
|
+
doneReading = done;
|
|
2327
|
+
if (done && !value) continue;
|
|
2328
|
+
try {
|
|
2329
|
+
const decoded = value ? new TextDecoder().decode(value) : "";
|
|
2330
|
+
const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
|
|
2331
|
+
buffer = chunks.pop() || "";
|
|
2332
|
+
for (const chunk of chunks) {
|
|
2333
|
+
if (chunk) {
|
|
2334
|
+
if (typeof chunk === "string") {
|
|
2335
|
+
try {
|
|
2336
|
+
const parsedChunk = JSON.parse(chunk);
|
|
2337
|
+
yield parsedChunk;
|
|
2338
|
+
} catch {
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
} catch {
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
if (buffer) {
|
|
2347
|
+
try {
|
|
2348
|
+
yield JSON.parse(buffer);
|
|
2349
|
+
} catch {
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
} finally {
|
|
2353
|
+
reader.cancel().catch(() => {
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Streams agent builder action progress in real-time.
|
|
2359
|
+
* This calls `/api/agent-builder/:actionId/stream`.
|
|
2360
|
+
*/
|
|
2361
|
+
async stream(params, runId) {
|
|
2362
|
+
const searchParams = new URLSearchParams();
|
|
2363
|
+
if (runId) {
|
|
2364
|
+
searchParams.set("runId", runId);
|
|
2365
|
+
}
|
|
2366
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2367
|
+
const { requestContext: _, ...actionParams } = params;
|
|
2368
|
+
const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
2369
|
+
const response = await this.request(url, {
|
|
2370
|
+
method: "POST",
|
|
2371
|
+
body: { ...actionParams, requestContext },
|
|
2372
|
+
stream: true
|
|
2373
|
+
});
|
|
2374
|
+
if (!response.ok) {
|
|
2375
|
+
throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
|
|
2376
|
+
}
|
|
2377
|
+
if (!response.body) {
|
|
2378
|
+
throw new Error("Response body is null");
|
|
2379
|
+
}
|
|
2380
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Streams agent builder action progress in real-time using VNext streaming.
|
|
2384
|
+
* This calls `/api/agent-builder/:actionId/streamVNext`.
|
|
2385
|
+
*/
|
|
2386
|
+
async streamVNext(params, runId) {
|
|
2387
|
+
const searchParams = new URLSearchParams();
|
|
2388
|
+
if (runId) {
|
|
2389
|
+
searchParams.set("runId", runId);
|
|
2390
|
+
}
|
|
2391
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2392
|
+
const { requestContext: _, ...actionParams } = params;
|
|
2393
|
+
const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
2394
|
+
const response = await this.request(url, {
|
|
2395
|
+
method: "POST",
|
|
2396
|
+
body: { ...actionParams, requestContext },
|
|
2397
|
+
stream: true
|
|
2398
|
+
});
|
|
2399
|
+
if (!response.ok) {
|
|
2400
|
+
throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
|
|
2401
|
+
}
|
|
2402
|
+
if (!response.body) {
|
|
2403
|
+
throw new Error("Response body is null");
|
|
2404
|
+
}
|
|
2405
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Observes an existing agent builder action run stream.
|
|
2409
|
+
* Replays cached execution from the beginning, then continues with live stream.
|
|
2410
|
+
* This is the recommended method for recovery after page refresh/hot reload.
|
|
2411
|
+
* This calls `/api/agent-builder/:actionId/observe` (which delegates to observeStreamVNext).
|
|
2412
|
+
*/
|
|
2413
|
+
async observeStream(params) {
|
|
2414
|
+
const searchParams = new URLSearchParams();
|
|
2415
|
+
searchParams.set("runId", params.runId);
|
|
2416
|
+
const url = `/api/agent-builder/${this.actionId}/observe?${searchParams.toString()}`;
|
|
2417
|
+
const response = await this.request(url, {
|
|
2418
|
+
method: "POST",
|
|
2419
|
+
stream: true
|
|
2420
|
+
});
|
|
2421
|
+
if (!response.ok) {
|
|
2422
|
+
throw new Error(`Failed to observe agent builder action stream: ${response.statusText}`);
|
|
2423
|
+
}
|
|
2424
|
+
if (!response.body) {
|
|
2425
|
+
throw new Error("Response body is null");
|
|
2426
|
+
}
|
|
2427
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* Observes an existing agent builder action run stream using VNext streaming API.
|
|
2431
|
+
* Replays cached execution from the beginning, then continues with live stream.
|
|
2432
|
+
* This calls `/api/agent-builder/:actionId/observe-streamVNext`.
|
|
2433
|
+
*/
|
|
2434
|
+
async observeStreamVNext(params) {
|
|
2435
|
+
const searchParams = new URLSearchParams();
|
|
2436
|
+
searchParams.set("runId", params.runId);
|
|
2437
|
+
const url = `/api/agent-builder/${this.actionId}/observe-streamVNext?${searchParams.toString()}`;
|
|
2438
|
+
const response = await this.request(url, {
|
|
2439
|
+
method: "POST",
|
|
2440
|
+
stream: true
|
|
2441
|
+
});
|
|
2442
|
+
if (!response.ok) {
|
|
2443
|
+
throw new Error(`Failed to observe agent builder action stream VNext: ${response.statusText}`);
|
|
2444
|
+
}
|
|
2445
|
+
if (!response.body) {
|
|
2446
|
+
throw new Error("Response body is null");
|
|
2447
|
+
}
|
|
2448
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* Observes an existing agent builder action run stream using legacy streaming API.
|
|
2452
|
+
* Replays cached execution from the beginning, then continues with live stream.
|
|
2453
|
+
* This calls `/api/agent-builder/:actionId/observe-stream-legacy`.
|
|
2454
|
+
*/
|
|
2455
|
+
async observeStreamLegacy(params) {
|
|
2456
|
+
const searchParams = new URLSearchParams();
|
|
2457
|
+
searchParams.set("runId", params.runId);
|
|
2458
|
+
const url = `/api/agent-builder/${this.actionId}/observe-stream-legacy?${searchParams.toString()}`;
|
|
2459
|
+
const response = await this.request(url, {
|
|
2460
|
+
method: "POST",
|
|
2461
|
+
stream: true
|
|
2462
|
+
});
|
|
2463
|
+
if (!response.ok) {
|
|
2464
|
+
throw new Error(`Failed to observe agent builder action stream legacy: ${response.statusText}`);
|
|
2465
|
+
}
|
|
2466
|
+
if (!response.body) {
|
|
2467
|
+
throw new Error("Response body is null");
|
|
2468
|
+
}
|
|
2469
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Resumes a suspended agent builder action and streams the results.
|
|
2473
|
+
* This calls `/api/agent-builder/:actionId/resume-stream`.
|
|
2474
|
+
*/
|
|
2475
|
+
async resumeStream(params) {
|
|
2476
|
+
const searchParams = new URLSearchParams();
|
|
2477
|
+
searchParams.set("runId", params.runId);
|
|
2478
|
+
const requestContext = parseClientRequestContext(params.requestContext);
|
|
2479
|
+
const { runId: _, requestContext: __, ...resumeParams } = params;
|
|
2480
|
+
const url = `/api/agent-builder/${this.actionId}/resume-stream?${searchParams.toString()}`;
|
|
2481
|
+
const response = await this.request(url, {
|
|
2482
|
+
method: "POST",
|
|
2483
|
+
body: { ...resumeParams, requestContext },
|
|
2484
|
+
stream: true
|
|
2485
|
+
});
|
|
2486
|
+
if (!response.ok) {
|
|
2487
|
+
throw new Error(`Failed to resume agent builder action stream: ${response.statusText}`);
|
|
2488
|
+
}
|
|
2489
|
+
if (!response.body) {
|
|
2490
|
+
throw new Error("Response body is null");
|
|
2491
|
+
}
|
|
2492
|
+
return response.body.pipeThrough(this.createRecordParserTransform());
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Gets a specific action run by its ID.
|
|
2496
|
+
* This calls `/api/agent-builder/:actionId/runs/:runId`.
|
|
2497
|
+
*/
|
|
2498
|
+
async runById(runId) {
|
|
2499
|
+
const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
|
|
2500
|
+
return this.request(url, {
|
|
2501
|
+
method: "GET"
|
|
2502
|
+
});
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Gets details about this agent builder action.
|
|
2506
|
+
* This calls `/api/agent-builder/:actionId`.
|
|
2507
|
+
*/
|
|
2508
|
+
async details() {
|
|
2509
|
+
const result = await this.request(`/api/agent-builder/${this.actionId}`);
|
|
2510
|
+
return result;
|
|
2511
|
+
}
|
|
2512
|
+
/**
|
|
2513
|
+
* Gets all runs for this agent builder action.
|
|
2514
|
+
* This calls `/api/agent-builder/:actionId/runs`.
|
|
2515
|
+
*/
|
|
2516
|
+
async runs(params) {
|
|
2517
|
+
const searchParams = new URLSearchParams();
|
|
2518
|
+
if (params?.fromDate) {
|
|
2519
|
+
searchParams.set("fromDate", params.fromDate.toISOString());
|
|
2520
|
+
}
|
|
2521
|
+
if (params?.toDate) {
|
|
2522
|
+
searchParams.set("toDate", params.toDate.toISOString());
|
|
2523
|
+
}
|
|
2524
|
+
if (params?.perPage !== void 0) {
|
|
2525
|
+
searchParams.set("perPage", String(params.perPage));
|
|
2526
|
+
}
|
|
2527
|
+
if (params?.page !== void 0) {
|
|
2528
|
+
searchParams.set("page", String(params.page));
|
|
2529
|
+
}
|
|
2530
|
+
if (params?.resourceId) {
|
|
2531
|
+
searchParams.set("resourceId", params.resourceId);
|
|
2532
|
+
}
|
|
2533
|
+
const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
|
|
2534
|
+
return this.request(url, {
|
|
2535
|
+
method: "GET"
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
/**
|
|
2539
|
+
* Gets the execution result of an agent builder action run.
|
|
2540
|
+
* This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
|
|
2541
|
+
*/
|
|
2542
|
+
async runExecutionResult(runId) {
|
|
2543
|
+
const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
|
|
2544
|
+
return this.request(url, {
|
|
2545
|
+
method: "GET"
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Cancels an agent builder action run.
|
|
2550
|
+
* This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
|
|
2551
|
+
*/
|
|
2552
|
+
async cancelRun(runId) {
|
|
2553
|
+
const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
|
|
2554
|
+
return this.request(url, {
|
|
2555
|
+
method: "POST"
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
};
|
|
2559
|
+
|
|
2560
|
+
// src/resources/observability.ts
|
|
2561
|
+
var Observability = class extends BaseResource {
|
|
2562
|
+
constructor(options) {
|
|
2563
|
+
super(options);
|
|
2564
|
+
}
|
|
2565
|
+
/**
|
|
2566
|
+
* Retrieves a specific trace by ID
|
|
2567
|
+
* @param traceId - ID of the trace to retrieve
|
|
2568
|
+
* @returns Promise containing the trace with all its spans
|
|
2569
|
+
*/
|
|
2570
|
+
getTrace(traceId) {
|
|
2571
|
+
return this.request(`/api/observability/traces/${traceId}`);
|
|
2572
|
+
}
|
|
2573
|
+
/**
|
|
2574
|
+
* Retrieves paginated list of traces with optional filtering
|
|
2575
|
+
* @param params - Parameters for pagination and filtering
|
|
2576
|
+
* @returns Promise containing paginated traces and pagination info
|
|
2577
|
+
*/
|
|
2578
|
+
getTraces(params) {
|
|
2579
|
+
const { pagination, filters } = params;
|
|
2580
|
+
const { page, perPage, dateRange } = pagination || {};
|
|
2581
|
+
const { name, spanType, entityId, entityType } = filters || {};
|
|
2582
|
+
const searchParams = new URLSearchParams();
|
|
2583
|
+
if (page !== void 0) {
|
|
2584
|
+
searchParams.set("page", String(page));
|
|
2585
|
+
}
|
|
2586
|
+
if (perPage !== void 0) {
|
|
2587
|
+
searchParams.set("perPage", String(perPage));
|
|
2588
|
+
}
|
|
2589
|
+
if (name) {
|
|
2590
|
+
searchParams.set("name", name);
|
|
2591
|
+
}
|
|
2592
|
+
if (spanType !== void 0) {
|
|
2593
|
+
searchParams.set("spanType", String(spanType));
|
|
2594
|
+
}
|
|
2595
|
+
if (entityId && entityType) {
|
|
2596
|
+
searchParams.set("entityId", entityId);
|
|
2597
|
+
searchParams.set("entityType", entityType);
|
|
2598
|
+
}
|
|
2599
|
+
if (dateRange) {
|
|
2600
|
+
const dateRangeStr = JSON.stringify({
|
|
2601
|
+
start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
|
|
2602
|
+
end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
|
|
2603
|
+
});
|
|
2604
|
+
searchParams.set("dateRange", dateRangeStr);
|
|
2605
|
+
}
|
|
2606
|
+
const queryString = searchParams.toString();
|
|
2607
|
+
return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* Retrieves scores by trace ID and span ID
|
|
2611
|
+
* @param params - Parameters containing trace ID, span ID, and pagination options
|
|
2612
|
+
* @returns Promise containing scores and pagination info
|
|
2613
|
+
*/
|
|
2614
|
+
listScoresBySpan(params) {
|
|
2615
|
+
const { traceId, spanId, page, perPage } = params;
|
|
2616
|
+
const searchParams = new URLSearchParams();
|
|
2617
|
+
if (page !== void 0) {
|
|
2618
|
+
searchParams.set("page", String(page));
|
|
2619
|
+
}
|
|
2620
|
+
if (perPage !== void 0) {
|
|
2621
|
+
searchParams.set("perPage", String(perPage));
|
|
2622
|
+
}
|
|
2623
|
+
const queryString = searchParams.toString();
|
|
2624
|
+
return this.request(
|
|
2625
|
+
`/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
|
|
2626
|
+
);
|
|
2627
|
+
}
|
|
2628
|
+
score(params) {
|
|
2629
|
+
return this.request(`/api/observability/traces/score`, {
|
|
2630
|
+
method: "POST",
|
|
2631
|
+
body: { ...params }
|
|
2632
|
+
});
|
|
2633
|
+
}
|
|
2634
|
+
};
|
|
2635
|
+
|
|
2636
|
+
// src/client.ts
|
|
2637
|
+
var MastraClient = class extends BaseResource {
|
|
2638
|
+
observability;
|
|
2639
|
+
constructor(options) {
|
|
2640
|
+
super(options);
|
|
2641
|
+
this.observability = new Observability(options);
|
|
2642
|
+
}
|
|
2643
|
+
/**
|
|
2644
|
+
* Retrieves all available agents
|
|
2645
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
2646
|
+
* @returns Promise containing map of agent IDs to agent details
|
|
2647
|
+
*/
|
|
2648
|
+
listAgents(requestContext) {
|
|
2649
|
+
const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
|
|
2650
|
+
const searchParams = new URLSearchParams();
|
|
2651
|
+
if (requestContextParam) {
|
|
2652
|
+
searchParams.set("requestContext", requestContextParam);
|
|
2653
|
+
}
|
|
2654
|
+
const queryString = searchParams.toString();
|
|
2655
|
+
return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
|
|
2656
|
+
}
|
|
2657
|
+
listAgentsModelProviders() {
|
|
2658
|
+
return this.request(`/api/agents/providers`);
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* Gets an agent instance by ID
|
|
2662
|
+
* @param agentId - ID of the agent to retrieve
|
|
2663
|
+
* @returns Agent instance
|
|
2664
|
+
*/
|
|
2665
|
+
getAgent(agentId) {
|
|
2666
|
+
return new Agent(this.options, agentId);
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Lists memory threads for a resource with pagination support
|
|
2670
|
+
* @param params - Parameters containing resource ID, pagination options, and optional request context
|
|
2671
|
+
* @returns Promise containing paginated array of memory threads with metadata
|
|
2672
|
+
*/
|
|
2673
|
+
async listMemoryThreads(params) {
|
|
2674
|
+
const queryParams = new URLSearchParams({
|
|
2675
|
+
resourceId: params.resourceId,
|
|
2676
|
+
resourceid: params.resourceId,
|
|
2677
|
+
agentId: params.agentId,
|
|
2678
|
+
...params.page !== void 0 && { page: params.page.toString() },
|
|
2679
|
+
...params.perPage !== void 0 && { perPage: params.perPage.toString() },
|
|
2680
|
+
...params.orderBy && { orderBy: params.orderBy },
|
|
2681
|
+
...params.sortDirection && { sortDirection: params.sortDirection }
|
|
2682
|
+
});
|
|
2683
|
+
const response = await this.request(
|
|
2684
|
+
`/api/memory/threads?${queryParams.toString()}${requestContextQueryString(params.requestContext, "&")}`
|
|
2685
|
+
);
|
|
2686
|
+
const actualResponse = "threads" in response ? response : {
|
|
2687
|
+
threads: response,
|
|
2688
|
+
total: response.length,
|
|
2689
|
+
page: params.page ?? 0,
|
|
2690
|
+
perPage: params.perPage ?? 100,
|
|
2691
|
+
hasMore: false
|
|
2692
|
+
};
|
|
2693
|
+
return actualResponse;
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* Retrieves memory config for a resource
|
|
2697
|
+
* @param params - Parameters containing the resource ID and optional request context
|
|
2698
|
+
* @returns Promise containing memory configuration
|
|
2699
|
+
*/
|
|
2700
|
+
getMemoryConfig(params) {
|
|
2701
|
+
return this.request(
|
|
2702
|
+
`/api/memory/config?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`
|
|
2703
|
+
);
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* Creates a new memory thread
|
|
2707
|
+
* @param params - Parameters for creating the memory thread including optional request context
|
|
2708
|
+
* @returns Promise containing the created memory thread
|
|
2709
|
+
*/
|
|
2710
|
+
createMemoryThread(params) {
|
|
2711
|
+
return this.request(
|
|
2712
|
+
`/api/memory/threads?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`,
|
|
2713
|
+
{ method: "POST", body: params }
|
|
2714
|
+
);
|
|
2715
|
+
}
|
|
2716
|
+
/**
|
|
2717
|
+
* Gets a memory thread instance by ID
|
|
2718
|
+
* @param threadId - ID of the memory thread to retrieve
|
|
2719
|
+
* @returns MemoryThread instance
|
|
2720
|
+
*/
|
|
2721
|
+
getMemoryThread({ threadId, agentId }) {
|
|
2722
|
+
return new MemoryThread(this.options, threadId, agentId);
|
|
2723
|
+
}
|
|
2724
|
+
listThreadMessages(threadId, opts = {}) {
|
|
2725
|
+
if (!opts.agentId && !opts.networkId) {
|
|
2726
|
+
throw new Error("Either agentId or networkId must be provided");
|
|
2727
|
+
}
|
|
2728
|
+
let url = "";
|
|
2729
|
+
if (opts.agentId) {
|
|
2730
|
+
url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}`;
|
|
2731
|
+
} else if (opts.networkId) {
|
|
2732
|
+
url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
|
|
2733
|
+
}
|
|
2734
|
+
return this.request(url);
|
|
2735
|
+
}
|
|
2736
|
+
deleteThread(threadId, opts = {}) {
|
|
2737
|
+
let url = "";
|
|
2738
|
+
if (opts.agentId) {
|
|
2739
|
+
url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}${requestContextQueryString(opts.requestContext, "&")}`;
|
|
2740
|
+
} else if (opts.networkId) {
|
|
2741
|
+
url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}${requestContextQueryString(opts.requestContext, "&")}`;
|
|
2742
|
+
}
|
|
2743
|
+
return this.request(url, { method: "DELETE" });
|
|
2744
|
+
}
|
|
2745
|
+
/**
|
|
2746
|
+
* Saves messages to memory
|
|
2747
|
+
* @param params - Parameters containing messages to save and optional request context
|
|
2748
|
+
* @returns Promise containing the saved messages
|
|
2749
|
+
*/
|
|
2750
|
+
saveMessageToMemory(params) {
|
|
2751
|
+
return this.request(
|
|
2752
|
+
`/api/memory/save-messages?agentId=${params.agentId}${requestContextQueryString(params.requestContext, "&")}`,
|
|
2753
|
+
{
|
|
2754
|
+
method: "POST",
|
|
2755
|
+
body: params
|
|
2756
|
+
}
|
|
2757
|
+
);
|
|
2758
|
+
}
|
|
2759
|
+
/**
|
|
2760
|
+
* Gets the status of the memory system
|
|
2761
|
+
* @param agentId - The agent ID
|
|
2762
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
2763
|
+
* @returns Promise containing memory system status
|
|
2764
|
+
*/
|
|
2765
|
+
getMemoryStatus(agentId, requestContext) {
|
|
2766
|
+
return this.request(`/api/memory/status?agentId=${agentId}${requestContextQueryString(requestContext, "&")}`);
|
|
2767
|
+
}
|
|
2768
|
+
/**
|
|
2769
|
+
* Retrieves all available tools
|
|
2770
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
2771
|
+
* @returns Promise containing map of tool IDs to tool details
|
|
2772
|
+
*/
|
|
2773
|
+
listTools(requestContext) {
|
|
2774
|
+
const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
|
|
2775
|
+
const searchParams = new URLSearchParams();
|
|
2776
|
+
if (requestContextParam) {
|
|
2777
|
+
searchParams.set("requestContext", requestContextParam);
|
|
2778
|
+
}
|
|
2779
|
+
const queryString = searchParams.toString();
|
|
2780
|
+
return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
|
|
2781
|
+
}
|
|
2782
|
+
/**
|
|
2783
|
+
* Gets a tool instance by ID
|
|
2784
|
+
* @param toolId - ID of the tool to retrieve
|
|
2785
|
+
* @returns Tool instance
|
|
2786
|
+
*/
|
|
2787
|
+
getTool(toolId) {
|
|
2788
|
+
return new Tool(this.options, toolId);
|
|
2789
|
+
}
|
|
2790
|
+
/**
|
|
2791
|
+
* Retrieves all available workflows
|
|
2792
|
+
* @param requestContext - Optional request context to pass as query parameter
|
|
2793
|
+
* @returns Promise containing map of workflow IDs to workflow details
|
|
2794
|
+
*/
|
|
2795
|
+
listWorkflows(requestContext) {
|
|
2796
|
+
const requestContextParam = base64RequestContext(parseClientRequestContext(requestContext));
|
|
2797
|
+
const searchParams = new URLSearchParams();
|
|
2798
|
+
if (requestContextParam) {
|
|
2799
|
+
searchParams.set("requestContext", requestContextParam);
|
|
2800
|
+
}
|
|
2801
|
+
const queryString = searchParams.toString();
|
|
2802
|
+
return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
|
|
2803
|
+
}
|
|
2804
|
+
/**
|
|
2805
|
+
* Gets a workflow instance by ID
|
|
2806
|
+
* @param workflowId - ID of the workflow to retrieve
|
|
2807
|
+
* @returns Workflow instance
|
|
2808
|
+
*/
|
|
2809
|
+
getWorkflow(workflowId) {
|
|
2810
|
+
return new Workflow(this.options, workflowId);
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* Gets all available agent builder actions
|
|
2814
|
+
* @returns Promise containing map of action IDs to action details
|
|
2815
|
+
*/
|
|
2816
|
+
getAgentBuilderActions() {
|
|
2817
|
+
return this.request("/api/agent-builder/");
|
|
2818
|
+
}
|
|
2819
|
+
/**
|
|
2820
|
+
* Gets an agent builder instance for executing agent-builder workflows
|
|
2821
|
+
* @returns AgentBuilder instance
|
|
2822
|
+
*/
|
|
2823
|
+
getAgentBuilderAction(actionId) {
|
|
2824
|
+
return new AgentBuilder(this.options, actionId);
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* Gets a vector instance by name
|
|
2828
|
+
* @param vectorName - Name of the vector to retrieve
|
|
2829
|
+
* @returns Vector instance
|
|
2830
|
+
*/
|
|
2831
|
+
getVector(vectorName) {
|
|
2832
|
+
return new Vector(this.options, vectorName);
|
|
2833
|
+
}
|
|
2834
|
+
/**
|
|
2835
|
+
* Retrieves logs
|
|
2836
|
+
* @param params - Parameters for filtering logs
|
|
2837
|
+
* @returns Promise containing array of log messages
|
|
2838
|
+
*/
|
|
2839
|
+
listLogs(params) {
|
|
2840
|
+
const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
|
|
2841
|
+
const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
|
|
2842
|
+
const searchParams = new URLSearchParams();
|
|
2843
|
+
if (transportId) {
|
|
2844
|
+
searchParams.set("transportId", transportId);
|
|
2845
|
+
}
|
|
2846
|
+
if (fromDate) {
|
|
2847
|
+
searchParams.set("fromDate", fromDate.toISOString());
|
|
2848
|
+
}
|
|
2849
|
+
if (toDate) {
|
|
2850
|
+
searchParams.set("toDate", toDate.toISOString());
|
|
2851
|
+
}
|
|
2852
|
+
if (logLevel) {
|
|
2853
|
+
searchParams.set("logLevel", logLevel);
|
|
2854
|
+
}
|
|
2855
|
+
if (page) {
|
|
2856
|
+
searchParams.set("page", String(page));
|
|
2857
|
+
}
|
|
2858
|
+
if (perPage) {
|
|
2859
|
+
searchParams.set("perPage", String(perPage));
|
|
2860
|
+
}
|
|
2861
|
+
if (_filters) {
|
|
2862
|
+
if (Array.isArray(_filters)) {
|
|
2863
|
+
for (const filter of _filters) {
|
|
2864
|
+
searchParams.append("filters", filter);
|
|
2865
|
+
}
|
|
2866
|
+
} else {
|
|
2867
|
+
searchParams.set("filters", _filters);
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
if (searchParams.size) {
|
|
2871
|
+
return this.request(`/api/logs?${searchParams}`);
|
|
2872
|
+
} else {
|
|
2873
|
+
return this.request(`/api/logs`);
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* Gets logs for a specific run
|
|
2878
|
+
* @param params - Parameters containing run ID to retrieve
|
|
2879
|
+
* @returns Promise containing array of log messages
|
|
2880
|
+
*/
|
|
2881
|
+
getLogForRun(params) {
|
|
2882
|
+
const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
|
|
2883
|
+
const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
|
|
2884
|
+
const searchParams = new URLSearchParams();
|
|
2885
|
+
if (runId) {
|
|
2886
|
+
searchParams.set("runId", runId);
|
|
2887
|
+
}
|
|
2888
|
+
if (transportId) {
|
|
2889
|
+
searchParams.set("transportId", transportId);
|
|
2890
|
+
}
|
|
2891
|
+
if (fromDate) {
|
|
2892
|
+
searchParams.set("fromDate", fromDate.toISOString());
|
|
2893
|
+
}
|
|
2894
|
+
if (toDate) {
|
|
2895
|
+
searchParams.set("toDate", toDate.toISOString());
|
|
2896
|
+
}
|
|
2897
|
+
if (logLevel) {
|
|
2898
|
+
searchParams.set("logLevel", logLevel);
|
|
2899
|
+
}
|
|
2900
|
+
if (page) {
|
|
2901
|
+
searchParams.set("page", String(page));
|
|
2902
|
+
}
|
|
2903
|
+
if (perPage) {
|
|
2904
|
+
searchParams.set("perPage", String(perPage));
|
|
2905
|
+
}
|
|
2906
|
+
if (_filters) {
|
|
2907
|
+
if (Array.isArray(_filters)) {
|
|
2908
|
+
for (const filter of _filters) {
|
|
2909
|
+
searchParams.append("filters", filter);
|
|
2910
|
+
}
|
|
2911
|
+
} else {
|
|
2912
|
+
searchParams.set("filters", _filters);
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
if (searchParams.size) {
|
|
2916
|
+
return this.request(`/api/logs/${runId}?${searchParams}`);
|
|
2917
|
+
} else {
|
|
2918
|
+
return this.request(`/api/logs/${runId}`);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
/**
|
|
2922
|
+
* List of all log transports
|
|
2923
|
+
* @returns Promise containing list of log transports
|
|
2924
|
+
*/
|
|
2925
|
+
listLogTransports() {
|
|
2926
|
+
return this.request("/api/logs/transports");
|
|
2927
|
+
}
|
|
2928
|
+
/**
|
|
2929
|
+
* Retrieves a list of available MCP servers.
|
|
2930
|
+
* @param params - Optional parameters for pagination (perPage, page).
|
|
2931
|
+
* @returns Promise containing the list of MCP servers and pagination info.
|
|
2932
|
+
*/
|
|
2933
|
+
getMcpServers(params) {
|
|
2934
|
+
const searchParams = new URLSearchParams();
|
|
2935
|
+
if (params?.perPage !== void 0) {
|
|
2936
|
+
searchParams.set("perPage", String(params.perPage));
|
|
2937
|
+
}
|
|
2938
|
+
if (params?.page !== void 0) {
|
|
2939
|
+
searchParams.set("page", String(params.page));
|
|
2940
|
+
}
|
|
2941
|
+
const queryString = searchParams.toString();
|
|
2942
|
+
return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
|
|
2943
|
+
}
|
|
2944
|
+
/**
|
|
2945
|
+
* Retrieves detailed information for a specific MCP server.
|
|
2946
|
+
* @param serverId - The ID of the MCP server to retrieve.
|
|
2947
|
+
* @param params - Optional parameters, e.g., specific version.
|
|
2948
|
+
* @returns Promise containing the detailed MCP server information.
|
|
2949
|
+
*/
|
|
2950
|
+
getMcpServerDetails(serverId, params) {
|
|
2951
|
+
const searchParams = new URLSearchParams();
|
|
2952
|
+
if (params?.version) {
|
|
2953
|
+
searchParams.set("version", params.version);
|
|
2954
|
+
}
|
|
2955
|
+
const queryString = searchParams.toString();
|
|
2956
|
+
return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
|
|
2957
|
+
}
|
|
2958
|
+
/**
|
|
2959
|
+
* Retrieves a list of tools for a specific MCP server.
|
|
2960
|
+
* @param serverId - The ID of the MCP server.
|
|
2961
|
+
* @returns Promise containing the list of tools.
|
|
2962
|
+
*/
|
|
2963
|
+
getMcpServerTools(serverId) {
|
|
2964
|
+
return this.request(`/api/mcp/${serverId}/tools`);
|
|
2965
|
+
}
|
|
2966
|
+
/**
|
|
2967
|
+
* Gets an MCPTool resource instance for a specific tool on an MCP server.
|
|
2968
|
+
* This instance can then be used to fetch details or execute the tool.
|
|
2969
|
+
* @param serverId - The ID of the MCP server.
|
|
2970
|
+
* @param toolId - The ID of the tool.
|
|
2971
|
+
* @returns MCPTool instance.
|
|
2972
|
+
*/
|
|
2973
|
+
getMcpServerTool(serverId, toolId) {
|
|
2974
|
+
return new MCPTool(this.options, serverId, toolId);
|
|
2975
|
+
}
|
|
2976
|
+
/**
|
|
2977
|
+
* Gets an A2A client for interacting with an agent via the A2A protocol
|
|
2978
|
+
* @param agentId - ID of the agent to interact with
|
|
2979
|
+
* @returns A2A client instance
|
|
2980
|
+
*/
|
|
2981
|
+
getA2A(agentId) {
|
|
2982
|
+
return new A2A(this.options, agentId);
|
|
2983
|
+
}
|
|
2984
|
+
/**
|
|
2985
|
+
* Retrieves the working memory for a specific thread (optionally resource-scoped).
|
|
2986
|
+
* @param agentId - ID of the agent.
|
|
2987
|
+
* @param threadId - ID of the thread.
|
|
2988
|
+
* @param resourceId - Optional ID of the resource.
|
|
2989
|
+
* @returns Working memory for the specified thread or resource.
|
|
2990
|
+
*/
|
|
2991
|
+
getWorkingMemory({
|
|
2992
|
+
agentId,
|
|
2993
|
+
threadId,
|
|
2994
|
+
resourceId,
|
|
2995
|
+
requestContext
|
|
2996
|
+
}) {
|
|
2997
|
+
return this.request(
|
|
2998
|
+
`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}${requestContextQueryString(requestContext, "&")}`
|
|
2999
|
+
);
|
|
3000
|
+
}
|
|
3001
|
+
searchMemory({
|
|
3002
|
+
agentId,
|
|
3003
|
+
resourceId,
|
|
3004
|
+
threadId,
|
|
3005
|
+
searchQuery,
|
|
3006
|
+
memoryConfig,
|
|
3007
|
+
requestContext
|
|
3008
|
+
}) {
|
|
3009
|
+
const params = new URLSearchParams({
|
|
3010
|
+
searchQuery,
|
|
3011
|
+
resourceId,
|
|
3012
|
+
agentId
|
|
3013
|
+
});
|
|
3014
|
+
if (threadId) {
|
|
3015
|
+
params.append("threadId", threadId);
|
|
3016
|
+
}
|
|
3017
|
+
if (memoryConfig) {
|
|
3018
|
+
params.append("memoryConfig", JSON.stringify(memoryConfig));
|
|
3019
|
+
}
|
|
3020
|
+
return this.request(`/api/memory/search?${params}${requestContextQueryString(requestContext, "&")}`);
|
|
3021
|
+
}
|
|
3022
|
+
/**
|
|
3023
|
+
* Updates the working memory for a specific thread (optionally resource-scoped).
|
|
3024
|
+
* @param agentId - ID of the agent.
|
|
3025
|
+
* @param threadId - ID of the thread.
|
|
3026
|
+
* @param workingMemory - The new working memory content.
|
|
3027
|
+
* @param resourceId - Optional ID of the resource.
|
|
3028
|
+
*/
|
|
3029
|
+
updateWorkingMemory({
|
|
3030
|
+
agentId,
|
|
3031
|
+
threadId,
|
|
3032
|
+
workingMemory,
|
|
3033
|
+
resourceId,
|
|
3034
|
+
requestContext
|
|
3035
|
+
}) {
|
|
3036
|
+
return this.request(
|
|
3037
|
+
`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}${requestContextQueryString(requestContext, "&")}`,
|
|
3038
|
+
{
|
|
3039
|
+
method: "POST",
|
|
3040
|
+
body: {
|
|
3041
|
+
workingMemory,
|
|
3042
|
+
resourceId
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
);
|
|
3046
|
+
}
|
|
3047
|
+
/**
|
|
3048
|
+
* Retrieves all available scorers
|
|
3049
|
+
* @returns Promise containing list of available scorers
|
|
3050
|
+
*/
|
|
3051
|
+
listScorers() {
|
|
3052
|
+
return this.request("/api/scores/scorers");
|
|
3053
|
+
}
|
|
3054
|
+
/**
|
|
3055
|
+
* Retrieves a scorer by ID
|
|
3056
|
+
* @param scorerId - ID of the scorer to retrieve
|
|
3057
|
+
* @returns Promise containing the scorer
|
|
3058
|
+
*/
|
|
3059
|
+
getScorer(scorerId) {
|
|
3060
|
+
return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
|
|
3061
|
+
}
|
|
3062
|
+
listScoresByScorerId(params) {
|
|
3063
|
+
const { page, perPage, scorerId, entityId, entityType } = params;
|
|
3064
|
+
const searchParams = new URLSearchParams();
|
|
3065
|
+
if (entityId) {
|
|
3066
|
+
searchParams.set("entityId", entityId);
|
|
3067
|
+
}
|
|
3068
|
+
if (entityType) {
|
|
3069
|
+
searchParams.set("entityType", entityType);
|
|
3070
|
+
}
|
|
3071
|
+
if (page !== void 0) {
|
|
3072
|
+
searchParams.set("page", String(page));
|
|
3073
|
+
}
|
|
3074
|
+
if (perPage !== void 0) {
|
|
3075
|
+
searchParams.set("perPage", String(perPage));
|
|
3076
|
+
}
|
|
3077
|
+
const queryString = searchParams.toString();
|
|
3078
|
+
return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
|
|
3079
|
+
}
|
|
3080
|
+
/**
|
|
3081
|
+
* Retrieves scores by run ID
|
|
3082
|
+
* @param params - Parameters containing run ID and pagination options
|
|
3083
|
+
* @returns Promise containing scores and pagination info
|
|
3084
|
+
*/
|
|
3085
|
+
listScoresByRunId(params) {
|
|
3086
|
+
const { runId, page, perPage } = params;
|
|
3087
|
+
const searchParams = new URLSearchParams();
|
|
3088
|
+
if (page !== void 0) {
|
|
3089
|
+
searchParams.set("page", String(page));
|
|
3090
|
+
}
|
|
3091
|
+
if (perPage !== void 0) {
|
|
3092
|
+
searchParams.set("perPage", String(perPage));
|
|
3093
|
+
}
|
|
3094
|
+
const queryString = searchParams.toString();
|
|
3095
|
+
return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
|
|
3096
|
+
}
|
|
3097
|
+
/**
|
|
3098
|
+
* Retrieves scores by entity ID and type
|
|
3099
|
+
* @param params - Parameters containing entity ID, type, and pagination options
|
|
3100
|
+
* @returns Promise containing scores and pagination info
|
|
3101
|
+
*/
|
|
3102
|
+
listScoresByEntityId(params) {
|
|
3103
|
+
const { entityId, entityType, page, perPage } = params;
|
|
3104
|
+
const searchParams = new URLSearchParams();
|
|
3105
|
+
if (page !== void 0) {
|
|
3106
|
+
searchParams.set("page", String(page));
|
|
3107
|
+
}
|
|
3108
|
+
if (perPage !== void 0) {
|
|
3109
|
+
searchParams.set("perPage", String(perPage));
|
|
3110
|
+
}
|
|
3111
|
+
const queryString = searchParams.toString();
|
|
3112
|
+
return this.request(
|
|
3113
|
+
`/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
|
|
3114
|
+
);
|
|
3115
|
+
}
|
|
3116
|
+
/**
|
|
3117
|
+
* Saves a score
|
|
3118
|
+
* @param params - Parameters containing the score data to save
|
|
3119
|
+
* @returns Promise containing the saved score
|
|
3120
|
+
*/
|
|
3121
|
+
saveScore(params) {
|
|
3122
|
+
return this.request("/api/scores", {
|
|
3123
|
+
method: "POST",
|
|
3124
|
+
body: params
|
|
3125
|
+
});
|
|
3126
|
+
}
|
|
3127
|
+
getTrace(traceId) {
|
|
3128
|
+
return this.observability.getTrace(traceId);
|
|
3129
|
+
}
|
|
3130
|
+
getTraces(params) {
|
|
3131
|
+
return this.observability.getTraces(params);
|
|
3132
|
+
}
|
|
3133
|
+
listScoresBySpan(params) {
|
|
3134
|
+
return this.observability.listScoresBySpan(params);
|
|
3135
|
+
}
|
|
3136
|
+
score(params) {
|
|
3137
|
+
return this.observability.score(params);
|
|
3138
|
+
}
|
|
3139
|
+
};
|
|
3140
|
+
|
|
3141
|
+
// src/tools.ts
|
|
3142
|
+
var ClientTool = class {
|
|
3143
|
+
id;
|
|
3144
|
+
description;
|
|
3145
|
+
inputSchema;
|
|
3146
|
+
outputSchema;
|
|
3147
|
+
execute;
|
|
3148
|
+
constructor(opts) {
|
|
3149
|
+
this.id = opts.id;
|
|
3150
|
+
this.description = opts.description;
|
|
3151
|
+
this.inputSchema = opts.inputSchema;
|
|
3152
|
+
this.outputSchema = opts.outputSchema;
|
|
3153
|
+
this.execute = opts.execute;
|
|
3154
|
+
}
|
|
3155
|
+
};
|
|
3156
|
+
function createTool(opts) {
|
|
3157
|
+
return new ClientTool(opts);
|
|
3158
|
+
}
|
|
3159
|
+
|
|
3160
|
+
export { ClientTool, MastraClient, createTool };
|
|
3161
|
+
//# sourceMappingURL=index.js.map
|
|
3162
|
+
//# sourceMappingURL=index.js.map
|