@mastra/client-js 0.0.0-course-20250527170450 → 0.0.0-createToolOptions-20250926094418

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