@mastra/client-js 0.0.0-add-runtime-context-to-openai-realtime-20250516201052 → 0.0.0-add-save-score-validation-on-stores-20250911031242

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