@mastra/client-js 0.0.0-inject-middleware-20250528222017 → 0.0.0-interpolate-reporter-url-20250910180021

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