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