@mastra/client-js 0.0.0-trigger-playground-ui-package-20250506151043 → 0.0.0-unified-sidebar-20251010130811

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