@mastra/client-js 0.0.0-vnext-inngest-20250508131921 → 0.0.0-vnext-20251104230439

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