@mastra/client-js 0.0.0-message-list-update-20250715150321 → 0.0.0-message-file-url-handling-fix-20250904234524

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 (81) hide show
  1. package/CHANGELOG.md +795 -3
  2. package/README.md +6 -3
  3. package/dist/client.d.ts +280 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/example.d.ts +2 -0
  6. package/dist/example.d.ts.map +1 -0
  7. package/dist/index.cjs +1627 -701
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.ts +4 -1194
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +1627 -701
  12. package/dist/index.js.map +1 -0
  13. package/dist/resources/a2a.d.ts +41 -0
  14. package/dist/resources/a2a.d.ts.map +1 -0
  15. package/dist/resources/agent-builder.d.ts +161 -0
  16. package/dist/resources/agent-builder.d.ts.map +1 -0
  17. package/dist/resources/agent.d.ts +155 -0
  18. package/dist/resources/agent.d.ts.map +1 -0
  19. package/dist/resources/base.d.ts +13 -0
  20. package/dist/resources/base.d.ts.map +1 -0
  21. package/dist/resources/index.d.ts +13 -0
  22. package/dist/resources/index.d.ts.map +1 -0
  23. package/dist/resources/legacy-workflow.d.ts +87 -0
  24. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  25. package/dist/resources/mcp-tool.d.ts +27 -0
  26. package/dist/resources/mcp-tool.d.ts.map +1 -0
  27. package/dist/resources/memory-thread.d.ts +53 -0
  28. package/dist/resources/memory-thread.d.ts.map +1 -0
  29. package/dist/resources/network-memory-thread.d.ts +47 -0
  30. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  31. package/dist/resources/network.d.ts +30 -0
  32. package/dist/resources/network.d.ts.map +1 -0
  33. package/dist/resources/observability.d.ts +19 -0
  34. package/dist/resources/observability.d.ts.map +1 -0
  35. package/dist/resources/tool.d.ts +23 -0
  36. package/dist/resources/tool.d.ts.map +1 -0
  37. package/dist/resources/vNextNetwork.d.ts +42 -0
  38. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  39. package/dist/resources/vector.d.ts +48 -0
  40. package/dist/resources/vector.d.ts.map +1 -0
  41. package/dist/resources/workflow.d.ts +154 -0
  42. package/dist/resources/workflow.d.ts.map +1 -0
  43. package/dist/types.d.ts +461 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/utils/index.d.ts +3 -0
  46. package/dist/utils/index.d.ts.map +1 -0
  47. package/dist/utils/process-client-tools.d.ts +3 -0
  48. package/dist/utils/process-client-tools.d.ts.map +1 -0
  49. package/dist/utils/process-mastra-stream.d.ts +7 -0
  50. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  51. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  52. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  53. package/package.json +26 -14
  54. package/.turbo/turbo-build.log +0 -19
  55. package/dist/index.d.cts +0 -1194
  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 -526
  60. package/src/example.ts +0 -95
  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 -800
  65. package/src/resources/base.ts +0 -72
  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-memory-thread.ts +0 -63
  71. package/src/resources/network.ts +0 -85
  72. package/src/resources/tool.ts +0 -45
  73. package/src/resources/vNextNetwork.ts +0 -194
  74. package/src/resources/vector.ts +0 -83
  75. package/src/resources/workflow.ts +0 -396
  76. package/src/types.ts +0 -428
  77. package/src/utils/index.ts +0 -11
  78. package/src/utils/process-client-tools.ts +0 -32
  79. package/src/utils/zod-to-json-schema.ts +0 -10
  80. package/tsconfig.json +0 -5
  81. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,216 +1,48 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
6
- var zod = require('zod');
7
- var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var tools = require('@mastra/core/tools');
9
4
  var uuid = require('@lukeed/uuid');
10
5
  var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
7
+ var zod = require('zod');
8
+ var originalZodToJsonSchema = require('zod-to-json-schema');
11
9
 
12
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
11
 
14
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
15
13
 
16
- // src/adapters/agui.ts
17
- var AGUIAdapter = class extends client.AbstractAgent {
18
- agent;
19
- resourceId;
20
- constructor({ agent, agentId, resourceId, ...rest }) {
21
- super({
22
- agentId,
23
- ...rest
24
- });
25
- this.agent = agent;
26
- this.resourceId = resourceId;
27
- }
28
- run(input) {
29
- return new rxjs.Observable((subscriber) => {
30
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
31
- subscriber.next({
32
- type: client.EventType.RUN_STARTED,
33
- threadId: input.threadId,
34
- runId: input.runId
35
- });
36
- this.agent.stream({
37
- threadId: input.threadId,
38
- resourceId: this.resourceId ?? "",
39
- runId: input.runId,
40
- messages: convertedMessages,
41
- clientTools: input.tools.reduce(
42
- (acc, tool) => {
43
- acc[tool.name] = {
44
- id: tool.name,
45
- description: tool.description,
46
- inputSchema: tool.parameters
47
- };
48
- return acc;
49
- },
50
- {}
51
- )
52
- }).then((response) => {
53
- let currentMessageId = void 0;
54
- let isInTextMessage = false;
55
- return response.processDataStream({
56
- onTextPart: (text) => {
57
- if (currentMessageId === void 0) {
58
- currentMessageId = generateUUID();
59
- const message2 = {
60
- type: client.EventType.TEXT_MESSAGE_START,
61
- messageId: currentMessageId,
62
- role: "assistant"
63
- };
64
- subscriber.next(message2);
65
- isInTextMessage = true;
66
- }
67
- const message = {
68
- type: client.EventType.TEXT_MESSAGE_CONTENT,
69
- messageId: currentMessageId,
70
- delta: text
71
- };
72
- subscriber.next(message);
73
- },
74
- onFinishMessagePart: () => {
75
- if (currentMessageId !== void 0) {
76
- const message = {
77
- type: client.EventType.TEXT_MESSAGE_END,
78
- messageId: currentMessageId
79
- };
80
- subscriber.next(message);
81
- isInTextMessage = false;
82
- }
83
- subscriber.next({
84
- type: client.EventType.RUN_FINISHED,
85
- threadId: input.threadId,
86
- runId: input.runId
87
- });
88
- subscriber.complete();
89
- },
90
- onToolCallPart(streamPart) {
91
- const parentMessageId = currentMessageId || generateUUID();
92
- if (isInTextMessage) {
93
- const message = {
94
- type: client.EventType.TEXT_MESSAGE_END,
95
- messageId: parentMessageId
96
- };
97
- subscriber.next(message);
98
- isInTextMessage = false;
99
- }
100
- subscriber.next({
101
- type: client.EventType.TOOL_CALL_START,
102
- toolCallId: streamPart.toolCallId,
103
- toolCallName: streamPart.toolName,
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: client.EventType.TOOL_CALL_ARGS,
108
- toolCallId: streamPart.toolCallId,
109
- delta: JSON.stringify(streamPart.args),
110
- parentMessageId
111
- });
112
- subscriber.next({
113
- type: client.EventType.TOOL_CALL_END,
114
- toolCallId: streamPart.toolCallId,
115
- parentMessageId
116
- });
117
- }
118
- });
119
- }).catch((error) => {
120
- console.error("error", error);
121
- subscriber.error(error);
122
- });
123
- return () => {
124
- };
125
- });
126
- }
127
- };
128
- function generateUUID() {
129
- if (typeof crypto !== "undefined") {
130
- if (typeof crypto.randomUUID === "function") {
131
- return crypto.randomUUID();
132
- }
133
- if (typeof crypto.getRandomValues === "function") {
134
- const buffer = new Uint8Array(16);
135
- crypto.getRandomValues(buffer);
136
- buffer[6] = buffer[6] & 15 | 64;
137
- buffer[8] = buffer[8] & 63 | 128;
138
- let hex = "";
139
- for (let i = 0; i < 16; i++) {
140
- hex += buffer[i].toString(16).padStart(2, "0");
141
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
142
- }
143
- return hex;
14
+ // src/resources/agent.ts
15
+ function parseClientRuntimeContext(runtimeContext$1) {
16
+ if (runtimeContext$1) {
17
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
18
+ return Object.fromEntries(runtimeContext$1.entries());
144
19
  }
20
+ return runtimeContext$1;
145
21
  }
146
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
147
- const r = Math.random() * 16 | 0;
148
- const v = c === "x" ? r : r & 3 | 8;
149
- return v.toString(16);
150
- });
22
+ return void 0;
151
23
  }
152
- function convertMessagesToMastraMessages(messages) {
153
- const result = [];
154
- for (const message of messages) {
155
- if (message.role === "assistant") {
156
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
157
- for (const toolCall of message.toolCalls ?? []) {
158
- parts.push({
159
- type: "tool-call",
160
- toolCallId: toolCall.id,
161
- toolName: toolCall.function.name,
162
- args: JSON.parse(toolCall.function.arguments)
163
- });
164
- }
165
- result.push({
166
- role: "assistant",
167
- content: parts
168
- });
169
- if (message.toolCalls?.length) {
170
- result.push({
171
- role: "tool",
172
- content: message.toolCalls.map((toolCall) => ({
173
- type: "tool-result",
174
- toolCallId: toolCall.id,
175
- toolName: toolCall.function.name,
176
- result: JSON.parse(toolCall.function.arguments)
177
- }))
178
- });
179
- }
180
- } else if (message.role === "user") {
181
- result.push({
182
- role: "user",
183
- content: message.content || ""
184
- });
185
- } else if (message.role === "tool") {
186
- result.push({
187
- role: "tool",
188
- content: [
189
- {
190
- type: "tool-result",
191
- toolCallId: message.toolCallId,
192
- toolName: "unknown",
193
- result: message.content
194
- }
195
- ]
196
- });
197
- }
198
- }
199
- return result;
24
+ function isZodType(value) {
25
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
200
26
  }
201
27
  function zodToJsonSchema(zodSchema) {
202
- if (!(zodSchema instanceof zod.ZodSchema)) {
28
+ if (!isZodType(zodSchema)) {
203
29
  return zodSchema;
204
30
  }
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
205
35
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
206
36
  }
37
+
38
+ // src/utils/process-client-tools.ts
207
39
  function processClientTools(clientTools) {
208
40
  if (!clientTools) {
209
41
  return void 0;
210
42
  }
211
43
  return Object.fromEntries(
212
44
  Object.entries(clientTools).map(([key, value]) => {
213
- if (tools.isVercelTool(value)) {
45
+ if (isVercelTool.isVercelTool(value)) {
214
46
  return [
215
47
  key,
216
48
  {
@@ -232,6 +64,42 @@ function processClientTools(clientTools) {
232
64
  );
233
65
  }
234
66
 
67
+ // src/utils/process-mastra-stream.ts
68
+ async function processMastraStream({
69
+ stream,
70
+ onChunk
71
+ }) {
72
+ const reader = stream.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read();
78
+ if (done) break;
79
+ buffer += decoder.decode(value, { stream: true });
80
+ const lines = buffer.split("\n\n");
81
+ buffer = lines.pop() || "";
82
+ for (const line of lines) {
83
+ if (line.startsWith("data: ")) {
84
+ const data = line.slice(6);
85
+ if (data === "[DONE]") {
86
+ console.log("\u{1F3C1} Stream finished");
87
+ return;
88
+ }
89
+ try {
90
+ const json = JSON.parse(data);
91
+ await onChunk(json);
92
+ } catch (error) {
93
+ console.error("\u274C JSON parse error:", error, "Data:", data);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ }
102
+
235
103
  // src/resources/base.ts
236
104
  var BaseResource = class {
237
105
  options;
@@ -246,20 +114,21 @@ var BaseResource = class {
246
114
  */
247
115
  async request(path, options = {}) {
248
116
  let lastError = null;
249
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
250
118
  let delay = backoffMs;
251
119
  for (let attempt = 0; attempt <= retries; attempt++) {
252
120
  try {
253
121
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
254
122
  ...options,
255
123
  headers: {
256
- ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
124
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
257
125
  ...headers,
258
126
  ...options.headers
259
127
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
260
128
  // 'x-mastra-client-type': 'js',
261
129
  },
262
130
  signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
263
132
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
264
133
  });
265
134
  if (!response.ok) {
@@ -292,14 +161,64 @@ var BaseResource = class {
292
161
  throw lastError || new Error("Request failed");
293
162
  }
294
163
  };
295
- function parseClientRuntimeContext(runtimeContext$1) {
296
- if (runtimeContext$1) {
297
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
298
- return Object.fromEntries(runtimeContext$1.entries());
164
+
165
+ // src/resources/agent.ts
166
+ async function executeToolCallAndRespond({
167
+ response,
168
+ params,
169
+ runId,
170
+ resourceId,
171
+ threadId,
172
+ runtimeContext,
173
+ respondFn
174
+ }) {
175
+ if (response.finishReason === "tool-calls") {
176
+ const toolCalls = response.toolCalls;
177
+ if (!toolCalls || !Array.isArray(toolCalls)) {
178
+ return response;
179
+ }
180
+ for (const toolCall of toolCalls) {
181
+ const clientTool = params.clientTools?.[toolCall.toolName];
182
+ if (clientTool && clientTool.execute) {
183
+ const result = await clientTool.execute(
184
+ {
185
+ context: toolCall?.args,
186
+ runId,
187
+ resourceId,
188
+ threadId,
189
+ runtimeContext,
190
+ tracingContext: { currentSpan: void 0 }
191
+ },
192
+ {
193
+ messages: response.messages,
194
+ toolCallId: toolCall?.toolCallId
195
+ }
196
+ );
197
+ const updatedMessages = [
198
+ {
199
+ role: "user",
200
+ content: params.messages
201
+ },
202
+ ...response.response.messages,
203
+ {
204
+ role: "tool",
205
+ content: [
206
+ {
207
+ type: "tool-result",
208
+ toolCallId: toolCall.toolCallId,
209
+ toolName: toolCall.toolName,
210
+ result
211
+ }
212
+ ]
213
+ }
214
+ ];
215
+ return respondFn({
216
+ ...params,
217
+ messages: updatedMessages
218
+ });
219
+ }
299
220
  }
300
- return runtimeContext$1;
301
221
  }
302
- return void 0;
303
222
  }
304
223
  var AgentVoice = class extends BaseResource {
305
224
  constructor(options, agentId) {
@@ -370,6 +289,12 @@ var Agent = class extends BaseResource {
370
289
  return this.request(`/api/agents/${this.agentId}`);
371
290
  }
372
291
  async generate(params) {
292
+ console.warn(
293
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th. Please use generateLegacy if you don't want to upgrade just yet."
294
+ );
295
+ return this.generateLegacy(params);
296
+ }
297
+ async generateLegacy(params) {
373
298
  const processedParams = {
374
299
  ...params,
375
300
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -378,10 +303,13 @@ var Agent = class extends BaseResource {
378
303
  clientTools: processClientTools(params.clientTools)
379
304
  };
380
305
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
381
- const response = await this.request(`/api/agents/${this.agentId}/generate`, {
382
- method: "POST",
383
- body: processedParams
384
- });
306
+ const response = await this.request(
307
+ `/api/agents/${this.agentId}/generate-legacy`,
308
+ {
309
+ method: "POST",
310
+ body: processedParams
311
+ }
312
+ );
385
313
  if (response.finishReason === "tool-calls") {
386
314
  const toolCalls = response.toolCalls;
387
315
  if (!toolCalls || !Array.isArray(toolCalls)) {
@@ -391,7 +319,14 @@ var Agent = class extends BaseResource {
391
319
  const clientTool = params.clientTools?.[toolCall.toolName];
392
320
  if (clientTool && clientTool.execute) {
393
321
  const result = await clientTool.execute(
394
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
322
+ {
323
+ context: toolCall?.args,
324
+ runId,
325
+ resourceId,
326
+ threadId,
327
+ runtimeContext,
328
+ tracingContext: { currentSpan: void 0 }
329
+ },
395
330
  {
396
331
  messages: response.messages,
397
332
  toolCallId: toolCall?.toolCallId
@@ -424,14 +359,41 @@ var Agent = class extends BaseResource {
424
359
  }
425
360
  return response;
426
361
  }
362
+ async generateVNext(params) {
363
+ const processedParams = {
364
+ ...params,
365
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
366
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
367
+ clientTools: processClientTools(params.clientTools)
368
+ };
369
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
370
+ const response = await this.request(
371
+ `/api/agents/${this.agentId}/generate/vnext`,
372
+ {
373
+ method: "POST",
374
+ body: processedParams
375
+ }
376
+ );
377
+ if (response.finishReason === "tool-calls") {
378
+ return executeToolCallAndRespond({
379
+ response,
380
+ params,
381
+ runId,
382
+ resourceId,
383
+ threadId,
384
+ runtimeContext,
385
+ respondFn: this.generateVNext.bind(this)
386
+ });
387
+ }
388
+ return response;
389
+ }
427
390
  async processChatResponse({
428
391
  stream,
429
392
  update,
430
393
  onToolCall,
431
394
  onFinish,
432
395
  getCurrentDate = () => /* @__PURE__ */ new Date(),
433
- lastMessage,
434
- streamProtocol
396
+ lastMessage
435
397
  }) {
436
398
  const replaceLastMessage = lastMessage?.role === "assistant";
437
399
  let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
@@ -492,257 +454,539 @@ var Agent = class extends BaseResource {
492
454
  replaceLastMessage
493
455
  });
494
456
  }
495
- if (streamProtocol === "text") {
496
- await uiUtils.processTextStream({
497
- stream,
498
- onTextPart(value) {
499
- message.content += value;
500
- execUpdate();
457
+ await uiUtils.processDataStream({
458
+ stream,
459
+ onTextPart(value) {
460
+ if (currentTextPart == null) {
461
+ currentTextPart = {
462
+ type: "text",
463
+ text: value
464
+ };
465
+ message.parts.push(currentTextPart);
466
+ } else {
467
+ currentTextPart.text += value;
501
468
  }
502
- });
503
- onFinish?.({ message, finishReason, usage });
504
- } else {
505
- await uiUtils.processDataStream({
506
- stream,
507
- onTextPart(value) {
508
- if (currentTextPart == null) {
509
- currentTextPart = {
510
- type: "text",
511
- text: value
512
- };
513
- message.parts.push(currentTextPart);
514
- } else {
515
- currentTextPart.text += value;
516
- }
517
- message.content += value;
518
- execUpdate();
519
- },
520
- onReasoningPart(value) {
521
- if (currentReasoningTextDetail == null) {
522
- currentReasoningTextDetail = { type: "text", text: value };
523
- if (currentReasoningPart != null) {
524
- currentReasoningPart.details.push(currentReasoningTextDetail);
525
- }
526
- } else {
527
- currentReasoningTextDetail.text += value;
528
- }
529
- if (currentReasoningPart == null) {
530
- currentReasoningPart = {
531
- type: "reasoning",
532
- reasoning: value,
533
- details: [currentReasoningTextDetail]
534
- };
535
- message.parts.push(currentReasoningPart);
536
- } else {
537
- currentReasoningPart.reasoning += value;
538
- }
539
- message.reasoning = (message.reasoning ?? "") + value;
540
- execUpdate();
541
- },
542
- onReasoningSignaturePart(value) {
543
- if (currentReasoningTextDetail != null) {
544
- currentReasoningTextDetail.signature = value.signature;
545
- }
546
- },
547
- onRedactedReasoningPart(value) {
548
- if (currentReasoningPart == null) {
549
- currentReasoningPart = {
550
- type: "reasoning",
551
- reasoning: "",
552
- details: []
553
- };
554
- message.parts.push(currentReasoningPart);
469
+ message.content += value;
470
+ execUpdate();
471
+ },
472
+ onReasoningPart(value) {
473
+ if (currentReasoningTextDetail == null) {
474
+ currentReasoningTextDetail = { type: "text", text: value };
475
+ if (currentReasoningPart != null) {
476
+ currentReasoningPart.details.push(currentReasoningTextDetail);
555
477
  }
556
- currentReasoningPart.details.push({
557
- type: "redacted",
558
- data: value.data
559
- });
560
- currentReasoningTextDetail = void 0;
561
- execUpdate();
562
- },
563
- onFilePart(value) {
564
- message.parts.push({
565
- type: "file",
566
- mimeType: value.mimeType,
567
- data: value.data
568
- });
569
- execUpdate();
570
- },
571
- onSourcePart(value) {
572
- message.parts.push({
573
- type: "source",
574
- source: value
575
- });
576
- execUpdate();
577
- },
578
- onToolCallStreamingStartPart(value) {
478
+ } else {
479
+ currentReasoningTextDetail.text += value;
480
+ }
481
+ if (currentReasoningPart == null) {
482
+ currentReasoningPart = {
483
+ type: "reasoning",
484
+ reasoning: value,
485
+ details: [currentReasoningTextDetail]
486
+ };
487
+ message.parts.push(currentReasoningPart);
488
+ } else {
489
+ currentReasoningPart.reasoning += value;
490
+ }
491
+ message.reasoning = (message.reasoning ?? "") + value;
492
+ execUpdate();
493
+ },
494
+ onReasoningSignaturePart(value) {
495
+ if (currentReasoningTextDetail != null) {
496
+ currentReasoningTextDetail.signature = value.signature;
497
+ }
498
+ },
499
+ onRedactedReasoningPart(value) {
500
+ if (currentReasoningPart == null) {
501
+ currentReasoningPart = {
502
+ type: "reasoning",
503
+ reasoning: "",
504
+ details: []
505
+ };
506
+ message.parts.push(currentReasoningPart);
507
+ }
508
+ currentReasoningPart.details.push({
509
+ type: "redacted",
510
+ data: value.data
511
+ });
512
+ currentReasoningTextDetail = void 0;
513
+ execUpdate();
514
+ },
515
+ onFilePart(value) {
516
+ message.parts.push({
517
+ type: "file",
518
+ mimeType: value.mimeType,
519
+ data: value.data
520
+ });
521
+ execUpdate();
522
+ },
523
+ onSourcePart(value) {
524
+ message.parts.push({
525
+ type: "source",
526
+ source: value
527
+ });
528
+ execUpdate();
529
+ },
530
+ onToolCallStreamingStartPart(value) {
531
+ if (message.toolInvocations == null) {
532
+ message.toolInvocations = [];
533
+ }
534
+ partialToolCalls[value.toolCallId] = {
535
+ text: "",
536
+ step,
537
+ toolName: value.toolName,
538
+ index: message.toolInvocations.length
539
+ };
540
+ const invocation = {
541
+ state: "partial-call",
542
+ step,
543
+ toolCallId: value.toolCallId,
544
+ toolName: value.toolName,
545
+ args: void 0
546
+ };
547
+ message.toolInvocations.push(invocation);
548
+ updateToolInvocationPart(value.toolCallId, invocation);
549
+ execUpdate();
550
+ },
551
+ onToolCallDeltaPart(value) {
552
+ const partialToolCall = partialToolCalls[value.toolCallId];
553
+ partialToolCall.text += value.argsTextDelta;
554
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
555
+ const invocation = {
556
+ state: "partial-call",
557
+ step: partialToolCall.step,
558
+ toolCallId: value.toolCallId,
559
+ toolName: partialToolCall.toolName,
560
+ args: partialArgs
561
+ };
562
+ message.toolInvocations[partialToolCall.index] = invocation;
563
+ updateToolInvocationPart(value.toolCallId, invocation);
564
+ execUpdate();
565
+ },
566
+ async onToolCallPart(value) {
567
+ const invocation = {
568
+ state: "call",
569
+ step,
570
+ ...value
571
+ };
572
+ if (partialToolCalls[value.toolCallId] != null) {
573
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
574
+ } else {
579
575
  if (message.toolInvocations == null) {
580
576
  message.toolInvocations = [];
581
577
  }
582
- partialToolCalls[value.toolCallId] = {
583
- text: "",
584
- step,
585
- toolName: value.toolName,
586
- index: message.toolInvocations.length
587
- };
588
- const invocation = {
589
- state: "partial-call",
590
- step,
591
- toolCallId: value.toolCallId,
592
- toolName: value.toolName,
593
- args: void 0
594
- };
595
578
  message.toolInvocations.push(invocation);
596
- updateToolInvocationPart(value.toolCallId, invocation);
597
- execUpdate();
598
- },
599
- onToolCallDeltaPart(value) {
600
- const partialToolCall = partialToolCalls[value.toolCallId];
601
- partialToolCall.text += value.argsTextDelta;
602
- const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
603
- const invocation = {
604
- state: "partial-call",
605
- step: partialToolCall.step,
606
- toolCallId: value.toolCallId,
607
- toolName: partialToolCall.toolName,
608
- args: partialArgs
609
- };
610
- message.toolInvocations[partialToolCall.index] = invocation;
611
- updateToolInvocationPart(value.toolCallId, invocation);
612
- execUpdate();
613
- },
614
- async onToolCallPart(value) {
615
- const invocation = {
616
- state: "call",
617
- step,
618
- ...value
619
- };
620
- if (partialToolCalls[value.toolCallId] != null) {
621
- message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
622
- } else {
623
- if (message.toolInvocations == null) {
624
- message.toolInvocations = [];
625
- }
626
- message.toolInvocations.push(invocation);
627
- }
628
- updateToolInvocationPart(value.toolCallId, invocation);
629
- execUpdate();
630
- if (onToolCall) {
631
- const result = await onToolCall({ toolCall: value });
632
- if (result != null) {
633
- const invocation2 = {
634
- state: "result",
635
- step,
636
- ...value,
637
- result
638
- };
639
- message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
640
- updateToolInvocationPart(value.toolCallId, invocation2);
641
- execUpdate();
642
- }
643
- }
644
- },
645
- onToolResultPart(value) {
646
- const toolInvocations = message.toolInvocations;
647
- if (toolInvocations == null) {
648
- throw new Error("tool_result must be preceded by a tool_call");
649
- }
650
- const toolInvocationIndex = toolInvocations.findIndex(
651
- (invocation2) => invocation2.toolCallId === value.toolCallId
652
- );
653
- if (toolInvocationIndex === -1) {
654
- throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
655
- }
656
- const invocation = {
657
- ...toolInvocations[toolInvocationIndex],
658
- state: "result",
659
- ...value
660
- };
661
- toolInvocations[toolInvocationIndex] = invocation;
662
- updateToolInvocationPart(value.toolCallId, invocation);
663
- execUpdate();
664
- },
665
- onDataPart(value) {
666
- data.push(...value);
667
- execUpdate();
668
- },
669
- onMessageAnnotationsPart(value) {
670
- if (messageAnnotations == null) {
671
- messageAnnotations = [...value];
672
- } else {
673
- messageAnnotations.push(...value);
674
- }
675
- execUpdate();
676
- },
677
- onFinishStepPart(value) {
678
- step += 1;
679
- currentTextPart = value.isContinued ? currentTextPart : void 0;
680
- currentReasoningPart = void 0;
681
- currentReasoningTextDetail = void 0;
682
- },
683
- onStartStepPart(value) {
684
- if (!replaceLastMessage) {
685
- message.id = value.messageId;
686
- }
687
- message.parts.push({ type: "step-start" });
688
- execUpdate();
689
- },
690
- onFinishMessagePart(value) {
691
- finishReason = value.finishReason;
692
- if (value.usage != null) {
693
- usage = value.usage;
579
+ }
580
+ updateToolInvocationPart(value.toolCallId, invocation);
581
+ execUpdate();
582
+ if (onToolCall) {
583
+ const result = await onToolCall({ toolCall: value });
584
+ if (result != null) {
585
+ const invocation2 = {
586
+ state: "result",
587
+ step,
588
+ ...value,
589
+ result
590
+ };
591
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
592
+ updateToolInvocationPart(value.toolCallId, invocation2);
593
+ execUpdate();
694
594
  }
695
- },
696
- onErrorPart(error) {
697
- throw new Error(error);
698
595
  }
699
- });
700
- onFinish?.({ message, finishReason, usage });
701
- }
596
+ },
597
+ onToolResultPart(value) {
598
+ const toolInvocations = message.toolInvocations;
599
+ if (toolInvocations == null) {
600
+ throw new Error("tool_result must be preceded by a tool_call");
601
+ }
602
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
603
+ if (toolInvocationIndex === -1) {
604
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
605
+ }
606
+ const invocation = {
607
+ ...toolInvocations[toolInvocationIndex],
608
+ state: "result",
609
+ ...value
610
+ };
611
+ toolInvocations[toolInvocationIndex] = invocation;
612
+ updateToolInvocationPart(value.toolCallId, invocation);
613
+ execUpdate();
614
+ },
615
+ onDataPart(value) {
616
+ data.push(...value);
617
+ execUpdate();
618
+ },
619
+ onMessageAnnotationsPart(value) {
620
+ if (messageAnnotations == null) {
621
+ messageAnnotations = [...value];
622
+ } else {
623
+ messageAnnotations.push(...value);
624
+ }
625
+ execUpdate();
626
+ },
627
+ onFinishStepPart(value) {
628
+ step += 1;
629
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
630
+ currentReasoningPart = void 0;
631
+ currentReasoningTextDetail = void 0;
632
+ },
633
+ onStartStepPart(value) {
634
+ if (!replaceLastMessage) {
635
+ message.id = value.messageId;
636
+ }
637
+ message.parts.push({ type: "step-start" });
638
+ execUpdate();
639
+ },
640
+ onFinishMessagePart(value) {
641
+ finishReason = value.finishReason;
642
+ if (value.usage != null) {
643
+ usage = value.usage;
644
+ }
645
+ },
646
+ onErrorPart(error) {
647
+ throw new Error(error);
648
+ }
649
+ });
650
+ onFinish?.({ message, finishReason, usage });
702
651
  }
703
652
  /**
704
- * Processes the stream response and handles tool calls
653
+ * Streams a response from the agent
654
+ * @param params - Stream parameters including prompt
655
+ * @returns Promise containing the enhanced Response object with processDataStream method
705
656
  */
706
- async processStreamResponse(processedParams, writable) {
707
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
708
- method: "POST",
709
- body: processedParams,
710
- stream: true
657
+ async stream(params) {
658
+ console.warn(
659
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th. Please use streamLegacy if you don't want to upgrade just yet."
660
+ );
661
+ return this.streamLegacy(params);
662
+ }
663
+ /**
664
+ * Streams a response from the agent
665
+ * @param params - Stream parameters including prompt
666
+ * @returns Promise containing the enhanced Response object with processDataStream method
667
+ */
668
+ async streamLegacy(params) {
669
+ const processedParams = {
670
+ ...params,
671
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
672
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
673
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
674
+ clientTools: processClientTools(params.clientTools)
675
+ };
676
+ const { readable, writable } = new TransformStream();
677
+ const response = await this.processStreamResponse(processedParams, writable);
678
+ const streamResponse = new Response(readable, {
679
+ status: response.status,
680
+ statusText: response.statusText,
681
+ headers: response.headers
711
682
  });
712
- if (!response.body) {
713
- throw new Error("No response body");
714
- }
715
- try {
716
- const streamProtocol = processedParams.output ? "text" : "data";
717
- let toolCalls = [];
718
- let messages = [];
719
- const [streamForWritable, streamForProcessing] = response.body.tee();
720
- streamForWritable.pipeTo(writable, {
721
- preventClose: true
722
- }).catch((error) => {
723
- console.error("Error piping to writable stream:", error);
683
+ streamResponse.processDataStream = async (options = {}) => {
684
+ await uiUtils.processDataStream({
685
+ stream: streamResponse.body,
686
+ ...options
724
687
  });
725
- this.processChatResponse({
726
- stream: streamForProcessing,
727
- update: ({ message }) => {
728
- messages.push(message);
729
- },
730
- onFinish: async ({ finishReason, message }) => {
731
- if (finishReason === "tool-calls") {
732
- const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
733
- if (toolCall) {
734
- toolCalls.push(toolCall);
735
- }
736
- for (const toolCall2 of toolCalls) {
737
- const clientTool = processedParams.clientTools?.[toolCall2.toolName];
738
- if (clientTool && clientTool.execute) {
739
- const result = await clientTool.execute(
688
+ };
689
+ return streamResponse;
690
+ }
691
+ async processChatResponse_vNext({
692
+ stream,
693
+ update,
694
+ onToolCall,
695
+ onFinish,
696
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
697
+ lastMessage
698
+ }) {
699
+ const replaceLastMessage = lastMessage?.role === "assistant";
700
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
701
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
702
+ return Math.max(max, toolInvocation.step ?? 0);
703
+ }, 0) ?? 0) : 0;
704
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
705
+ id: uuid.v4(),
706
+ createdAt: getCurrentDate(),
707
+ role: "assistant",
708
+ content: "",
709
+ parts: []
710
+ };
711
+ let currentTextPart = void 0;
712
+ let currentReasoningPart = void 0;
713
+ let currentReasoningTextDetail = void 0;
714
+ function updateToolInvocationPart(toolCallId, invocation) {
715
+ const part = message.parts.find(
716
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
717
+ );
718
+ if (part != null) {
719
+ part.toolInvocation = invocation;
720
+ } else {
721
+ message.parts.push({
722
+ type: "tool-invocation",
723
+ toolInvocation: invocation
724
+ });
725
+ }
726
+ }
727
+ const data = [];
728
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
729
+ const partialToolCalls = {};
730
+ let usage = {
731
+ completionTokens: NaN,
732
+ promptTokens: NaN,
733
+ totalTokens: NaN
734
+ };
735
+ let finishReason = "unknown";
736
+ function execUpdate() {
737
+ const copiedData = [...data];
738
+ if (messageAnnotations?.length) {
739
+ message.annotations = messageAnnotations;
740
+ }
741
+ const copiedMessage = {
742
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
743
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
744
+ ...structuredClone(message),
745
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
746
+ // hashing approach by default to detect changes, but it only works for shallow
747
+ // changes. This is why we need to add a revision id to ensure that the message
748
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
749
+ // forwarded to rendering):
750
+ revisionId: uuid.v4()
751
+ };
752
+ update({
753
+ message: copiedMessage,
754
+ data: copiedData,
755
+ replaceLastMessage
756
+ });
757
+ }
758
+ await processMastraStream({
759
+ stream,
760
+ // TODO: casting as any here because the stream types were all typed as any before in core.
761
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
762
+ onChunk: async (chunk) => {
763
+ switch (chunk.type) {
764
+ case "step-start": {
765
+ if (!replaceLastMessage) {
766
+ message.id = chunk.payload.messageId;
767
+ }
768
+ message.parts.push({ type: "step-start" });
769
+ execUpdate();
770
+ break;
771
+ }
772
+ case "text-delta": {
773
+ if (currentTextPart == null) {
774
+ currentTextPart = {
775
+ type: "text",
776
+ text: chunk.payload.text
777
+ };
778
+ message.parts.push(currentTextPart);
779
+ } else {
780
+ currentTextPart.text += chunk.payload.text;
781
+ }
782
+ message.content += chunk.payload.text;
783
+ execUpdate();
784
+ break;
785
+ }
786
+ case "reasoning-delta": {
787
+ if (currentReasoningTextDetail == null) {
788
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
789
+ if (currentReasoningPart != null) {
790
+ currentReasoningPart.details.push(currentReasoningTextDetail);
791
+ }
792
+ } else {
793
+ currentReasoningTextDetail.text += chunk.payload.text;
794
+ }
795
+ if (currentReasoningPart == null) {
796
+ currentReasoningPart = {
797
+ type: "reasoning",
798
+ reasoning: chunk.payload.text,
799
+ details: [currentReasoningTextDetail]
800
+ };
801
+ message.parts.push(currentReasoningPart);
802
+ } else {
803
+ currentReasoningPart.reasoning += chunk.payload.text;
804
+ }
805
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
806
+ execUpdate();
807
+ break;
808
+ }
809
+ case "file": {
810
+ message.parts.push({
811
+ type: "file",
812
+ mimeType: chunk.payload.mimeType,
813
+ data: chunk.payload.data
814
+ });
815
+ execUpdate();
816
+ break;
817
+ }
818
+ case "source": {
819
+ message.parts.push({
820
+ type: "source",
821
+ source: chunk.payload.source
822
+ });
823
+ execUpdate();
824
+ break;
825
+ }
826
+ case "tool-call": {
827
+ const invocation = {
828
+ state: "call",
829
+ step,
830
+ ...chunk.payload
831
+ };
832
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
833
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
834
+ } else {
835
+ if (message.toolInvocations == null) {
836
+ message.toolInvocations = [];
837
+ }
838
+ message.toolInvocations.push(invocation);
839
+ }
840
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
841
+ execUpdate();
842
+ if (onToolCall) {
843
+ const result = await onToolCall({ toolCall: chunk.payload });
844
+ if (result != null) {
845
+ const invocation2 = {
846
+ state: "result",
847
+ step,
848
+ ...chunk.payload,
849
+ result
850
+ };
851
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
852
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
853
+ execUpdate();
854
+ }
855
+ }
856
+ }
857
+ case "tool-call-input-streaming-start": {
858
+ if (message.toolInvocations == null) {
859
+ message.toolInvocations = [];
860
+ }
861
+ partialToolCalls[chunk.payload.toolCallId] = {
862
+ text: "",
863
+ step,
864
+ toolName: chunk.payload.toolName,
865
+ index: message.toolInvocations.length
866
+ };
867
+ const invocation = {
868
+ state: "partial-call",
869
+ step,
870
+ toolCallId: chunk.payload.toolCallId,
871
+ toolName: chunk.payload.toolName,
872
+ args: void 0
873
+ };
874
+ message.toolInvocations.push(invocation);
875
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
876
+ execUpdate();
877
+ break;
878
+ }
879
+ case "tool-call-delta": {
880
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
881
+ partialToolCall.text += chunk.payload.argsTextDelta;
882
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
883
+ const invocation = {
884
+ state: "partial-call",
885
+ step: partialToolCall.step,
886
+ toolCallId: chunk.payload.toolCallId,
887
+ toolName: partialToolCall.toolName,
888
+ args: partialArgs
889
+ };
890
+ message.toolInvocations[partialToolCall.index] = invocation;
891
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
892
+ execUpdate();
893
+ break;
894
+ }
895
+ case "tool-result": {
896
+ const toolInvocations = message.toolInvocations;
897
+ if (toolInvocations == null) {
898
+ throw new Error("tool_result must be preceded by a tool_call");
899
+ }
900
+ const toolInvocationIndex = toolInvocations.findIndex(
901
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
902
+ );
903
+ if (toolInvocationIndex === -1) {
904
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
905
+ }
906
+ const invocation = {
907
+ ...toolInvocations[toolInvocationIndex],
908
+ state: "result",
909
+ ...chunk.payload
910
+ };
911
+ toolInvocations[toolInvocationIndex] = invocation;
912
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
913
+ execUpdate();
914
+ break;
915
+ }
916
+ case "error": {
917
+ throw new Error(chunk.payload.error);
918
+ }
919
+ case "data": {
920
+ data.push(...chunk.payload.data);
921
+ execUpdate();
922
+ break;
923
+ }
924
+ case "step-finish": {
925
+ step += 1;
926
+ currentTextPart = chunk.payload.isContinued ? currentTextPart : void 0;
927
+ currentReasoningPart = void 0;
928
+ currentReasoningTextDetail = void 0;
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "finish": {
933
+ finishReason = chunk.payload.finishReason;
934
+ if (chunk.payload.usage != null) {
935
+ usage = chunk.payload.usage;
936
+ }
937
+ break;
938
+ }
939
+ }
940
+ }
941
+ });
942
+ onFinish?.({ message, finishReason, usage });
943
+ }
944
+ async processStreamResponse_vNext(processedParams, writable) {
945
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
946
+ method: "POST",
947
+ body: processedParams,
948
+ stream: true
949
+ });
950
+ if (!response.body) {
951
+ throw new Error("No response body");
952
+ }
953
+ try {
954
+ let toolCalls = [];
955
+ let messages = [];
956
+ const [streamForWritable, streamForProcessing] = response.body.tee();
957
+ streamForWritable.pipeTo(writable, {
958
+ preventClose: true
959
+ }).catch((error) => {
960
+ console.error("Error piping to writable stream:", error);
961
+ });
962
+ this.processChatResponse_vNext({
963
+ stream: streamForProcessing,
964
+ update: ({ message }) => {
965
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
966
+ if (existingIndex !== -1) {
967
+ messages[existingIndex] = message;
968
+ } else {
969
+ messages.push(message);
970
+ }
971
+ },
972
+ onFinish: async ({ finishReason, message }) => {
973
+ if (finishReason === "tool-calls") {
974
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
975
+ if (toolCall) {
976
+ toolCalls.push(toolCall);
977
+ }
978
+ for (const toolCall2 of toolCalls) {
979
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
980
+ if (clientTool && clientTool.execute) {
981
+ const result = await clientTool.execute(
740
982
  {
741
983
  context: toolCall2?.args,
742
984
  runId: processedParams.runId,
743
985
  resourceId: processedParams.resourceId,
744
986
  threadId: processedParams.threadId,
745
- runtimeContext: processedParams.runtimeContext
987
+ runtimeContext: processedParams.runtimeContext,
988
+ // TODO: Pass proper tracing context when client-js supports tracing
989
+ tracingContext: { currentSpan: void 0 }
746
990
  },
747
991
  {
748
992
  messages: response.messages,
@@ -782,145 +1026,61 @@ var Agent = class extends BaseResource {
782
1026
  }
783
1027
  const originalMessages = processedParams.messages;
784
1028
  const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
785
- this.processStreamResponse(
1029
+ this.processStreamResponse_vNext(
786
1030
  {
787
1031
  ...processedParams,
788
- messages: [...messageArray, ...messages, lastMessage]
1032
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
789
1033
  },
790
1034
  writable
791
- );
1035
+ ).catch((error) => {
1036
+ console.error("Error processing stream response:", error);
1037
+ });
792
1038
  }
793
1039
  }
794
1040
  } else {
795
1041
  setTimeout(() => {
796
- if (!writable.locked) {
797
- writable.close();
798
- }
1042
+ writable.close();
799
1043
  }, 0);
800
1044
  }
801
1045
  },
802
- lastMessage: void 0,
803
- streamProtocol
1046
+ lastMessage: void 0
1047
+ }).catch((error) => {
1048
+ console.error("Error processing stream response:", error);
804
1049
  });
805
1050
  } catch (error) {
806
1051
  console.error("Error processing stream response:", error);
807
1052
  }
808
1053
  return response;
809
1054
  }
810
- /**
811
- * Streams a response from the agent
812
- * @param params - Stream parameters including prompt
813
- * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
814
- */
815
- async stream(params) {
1055
+ async streamVNext(params) {
816
1056
  const processedParams = {
817
1057
  ...params,
818
1058
  output: params.output ? zodToJsonSchema(params.output) : void 0,
819
- experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
820
1059
  runtimeContext: parseClientRuntimeContext(params.runtimeContext),
821
1060
  clientTools: processClientTools(params.clientTools)
822
1061
  };
823
1062
  const { readable, writable } = new TransformStream();
824
- const response = await this.processStreamResponse(processedParams, writable);
1063
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
825
1064
  const streamResponse = new Response(readable, {
826
1065
  status: response.status,
827
1066
  statusText: response.statusText,
828
1067
  headers: response.headers
829
1068
  });
830
- streamResponse.processDataStream = async (options = {}) => {
831
- await uiUtils.processDataStream({
832
- stream: streamResponse.body,
833
- ...options
834
- });
835
- };
836
- streamResponse.processTextStream = async (options) => {
837
- await uiUtils.processTextStream({
1069
+ streamResponse.processDataStream = async ({
1070
+ onChunk
1071
+ }) => {
1072
+ await processMastraStream({
838
1073
  stream: streamResponse.body,
839
- onTextPart: options?.onTextPart ?? (() => {
840
- })
1074
+ onChunk
841
1075
  });
842
1076
  };
843
1077
  return streamResponse;
844
1078
  }
845
1079
  /**
846
- * Gets details about a specific tool available to the agent
847
- * @param toolId - ID of the tool to retrieve
848
- * @returns Promise containing tool details
849
- */
850
- getTool(toolId) {
851
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
852
- }
853
- /**
854
- * Executes a tool for the agent
855
- * @param toolId - ID of the tool to execute
856
- * @param params - Parameters required for tool execution
857
- * @returns Promise containing the tool execution results
858
- */
859
- executeTool(toolId, params) {
860
- const body = {
861
- data: params.data,
862
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
863
- };
864
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
865
- method: "POST",
866
- body
867
- });
868
- }
869
- /**
870
- * Retrieves evaluation results for the agent
871
- * @returns Promise containing agent evaluations
872
- */
873
- evals() {
874
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
875
- }
876
- /**
877
- * Retrieves live evaluation results for the agent
878
- * @returns Promise containing live agent evaluations
879
- */
880
- liveEvals() {
881
- return this.request(`/api/agents/${this.agentId}/evals/live`);
882
- }
883
- };
884
- var Network = class extends BaseResource {
885
- constructor(options, networkId) {
886
- super(options);
887
- this.networkId = networkId;
888
- }
889
- /**
890
- * Retrieves details about the network
891
- * @returns Promise containing network details
892
- */
893
- details() {
894
- return this.request(`/api/networks/${this.networkId}`);
895
- }
896
- /**
897
- * Generates a response from the agent
898
- * @param params - Generation parameters including prompt
899
- * @returns Promise containing the generated response
900
- */
901
- generate(params) {
902
- const processedParams = {
903
- ...params,
904
- output: zodToJsonSchema(params.output),
905
- experimental_output: zodToJsonSchema(params.experimental_output)
906
- };
907
- return this.request(`/api/networks/${this.networkId}/generate`, {
908
- method: "POST",
909
- body: processedParams
910
- });
911
- }
912
- /**
913
- * Streams a response from the agent
914
- * @param params - Stream parameters including prompt
915
- * @returns Promise containing the enhanced Response object with processDataStream method
1080
+ * Processes the stream response and handles tool calls
916
1081
  */
917
- async stream(params) {
918
- const processedParams = {
919
- ...params,
920
- output: zodToJsonSchema(params.output),
921
- experimental_output: zodToJsonSchema(params.experimental_output)
922
- };
923
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1082
+ async processStreamResponse(processedParams, writable) {
1083
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
924
1084
  method: "POST",
925
1085
  body: processedParams,
926
1086
  stream: true
@@ -928,17 +1088,216 @@ var Network = class extends BaseResource {
928
1088
  if (!response.body) {
929
1089
  throw new Error("No response body");
930
1090
  }
931
- response.processDataStream = async (options = {}) => {
932
- await uiUtils.processDataStream({
933
- stream: response.body,
934
- ...options
1091
+ try {
1092
+ let toolCalls = [];
1093
+ let messages = [];
1094
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1095
+ streamForWritable.pipeTo(writable, {
1096
+ preventClose: true
1097
+ }).catch((error) => {
1098
+ console.error("Error piping to writable stream:", error);
935
1099
  });
936
- };
937
- return response;
938
- }
939
- };
940
-
941
- // src/resources/memory-thread.ts
1100
+ this.processChatResponse({
1101
+ stream: streamForProcessing,
1102
+ update: ({ message }) => {
1103
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1104
+ if (existingIndex !== -1) {
1105
+ messages[existingIndex] = message;
1106
+ } else {
1107
+ messages.push(message);
1108
+ }
1109
+ },
1110
+ onFinish: async ({ finishReason, message }) => {
1111
+ if (finishReason === "tool-calls") {
1112
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1113
+ if (toolCall) {
1114
+ toolCalls.push(toolCall);
1115
+ }
1116
+ for (const toolCall2 of toolCalls) {
1117
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1118
+ if (clientTool && clientTool.execute) {
1119
+ const result = await clientTool.execute(
1120
+ {
1121
+ context: toolCall2?.args,
1122
+ runId: processedParams.runId,
1123
+ resourceId: processedParams.resourceId,
1124
+ threadId: processedParams.threadId,
1125
+ runtimeContext: processedParams.runtimeContext,
1126
+ // TODO: Pass proper tracing context when client-js supports tracing
1127
+ tracingContext: { currentSpan: void 0 }
1128
+ },
1129
+ {
1130
+ messages: response.messages,
1131
+ toolCallId: toolCall2?.toolCallId
1132
+ }
1133
+ );
1134
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1135
+ const toolInvocationPart = lastMessage?.parts?.find(
1136
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1137
+ );
1138
+ if (toolInvocationPart) {
1139
+ toolInvocationPart.toolInvocation = {
1140
+ ...toolInvocationPart.toolInvocation,
1141
+ state: "result",
1142
+ result
1143
+ };
1144
+ }
1145
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1146
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1147
+ );
1148
+ if (toolInvocation) {
1149
+ toolInvocation.state = "result";
1150
+ toolInvocation.result = result;
1151
+ }
1152
+ const writer = writable.getWriter();
1153
+ try {
1154
+ await writer.write(
1155
+ new TextEncoder().encode(
1156
+ "a:" + JSON.stringify({
1157
+ toolCallId: toolCall2.toolCallId,
1158
+ result
1159
+ }) + "\n"
1160
+ )
1161
+ );
1162
+ } finally {
1163
+ writer.releaseLock();
1164
+ }
1165
+ const originalMessages = processedParams.messages;
1166
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1167
+ this.processStreamResponse(
1168
+ {
1169
+ ...processedParams,
1170
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1171
+ },
1172
+ writable
1173
+ ).catch((error) => {
1174
+ console.error("Error processing stream response:", error);
1175
+ });
1176
+ }
1177
+ }
1178
+ } else {
1179
+ setTimeout(() => {
1180
+ writable.close();
1181
+ }, 0);
1182
+ }
1183
+ },
1184
+ lastMessage: void 0
1185
+ }).catch((error) => {
1186
+ console.error("Error processing stream response:", error);
1187
+ });
1188
+ } catch (error) {
1189
+ console.error("Error processing stream response:", error);
1190
+ }
1191
+ return response;
1192
+ }
1193
+ /**
1194
+ * Gets details about a specific tool available to the agent
1195
+ * @param toolId - ID of the tool to retrieve
1196
+ * @returns Promise containing tool details
1197
+ */
1198
+ getTool(toolId) {
1199
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1200
+ }
1201
+ /**
1202
+ * Executes a tool for the agent
1203
+ * @param toolId - ID of the tool to execute
1204
+ * @param params - Parameters required for tool execution
1205
+ * @returns Promise containing the tool execution results
1206
+ */
1207
+ executeTool(toolId, params) {
1208
+ const body = {
1209
+ data: params.data,
1210
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1211
+ };
1212
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1213
+ method: "POST",
1214
+ body
1215
+ });
1216
+ }
1217
+ /**
1218
+ * Retrieves evaluation results for the agent
1219
+ * @returns Promise containing agent evaluations
1220
+ */
1221
+ evals() {
1222
+ return this.request(`/api/agents/${this.agentId}/evals/ci`);
1223
+ }
1224
+ /**
1225
+ * Retrieves live evaluation results for the agent
1226
+ * @returns Promise containing live agent evaluations
1227
+ */
1228
+ liveEvals() {
1229
+ return this.request(`/api/agents/${this.agentId}/evals/live`);
1230
+ }
1231
+ /**
1232
+ * Updates the model for the agent
1233
+ * @param params - Parameters for updating the model
1234
+ * @returns Promise containing the updated model
1235
+ */
1236
+ updateModel(params) {
1237
+ return this.request(`/api/agents/${this.agentId}/model`, {
1238
+ method: "POST",
1239
+ body: params
1240
+ });
1241
+ }
1242
+ };
1243
+ var Network = class extends BaseResource {
1244
+ constructor(options, networkId) {
1245
+ super(options);
1246
+ this.networkId = networkId;
1247
+ }
1248
+ /**
1249
+ * Retrieves details about the network
1250
+ * @returns Promise containing network details
1251
+ */
1252
+ details() {
1253
+ return this.request(`/api/networks/${this.networkId}`);
1254
+ }
1255
+ /**
1256
+ * Generates a response from the agent
1257
+ * @param params - Generation parameters including prompt
1258
+ * @returns Promise containing the generated response
1259
+ */
1260
+ generate(params) {
1261
+ const processedParams = {
1262
+ ...params,
1263
+ output: zodToJsonSchema(params.output),
1264
+ experimental_output: zodToJsonSchema(params.experimental_output)
1265
+ };
1266
+ return this.request(`/api/networks/${this.networkId}/generate`, {
1267
+ method: "POST",
1268
+ body: processedParams
1269
+ });
1270
+ }
1271
+ /**
1272
+ * Streams a response from the agent
1273
+ * @param params - Stream parameters including prompt
1274
+ * @returns Promise containing the enhanced Response object with processDataStream method
1275
+ */
1276
+ async stream(params) {
1277
+ const processedParams = {
1278
+ ...params,
1279
+ output: zodToJsonSchema(params.output),
1280
+ experimental_output: zodToJsonSchema(params.experimental_output)
1281
+ };
1282
+ const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1283
+ method: "POST",
1284
+ body: processedParams,
1285
+ stream: true
1286
+ });
1287
+ if (!response.body) {
1288
+ throw new Error("No response body");
1289
+ }
1290
+ response.processDataStream = async (options = {}) => {
1291
+ await uiUtils.processDataStream({
1292
+ stream: response.body,
1293
+ ...options
1294
+ });
1295
+ };
1296
+ return response;
1297
+ }
1298
+ };
1299
+
1300
+ // src/resources/memory-thread.ts
942
1301
  var MemoryThread = class extends BaseResource {
943
1302
  constructor(options, threadId, agentId) {
944
1303
  super(options);
@@ -984,6 +1343,36 @@ var MemoryThread = class extends BaseResource {
984
1343
  });
985
1344
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
986
1345
  }
1346
+ /**
1347
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1348
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1349
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1350
+ */
1351
+ getMessagesPaginated({
1352
+ selectBy,
1353
+ ...rest
1354
+ }) {
1355
+ const query = new URLSearchParams({
1356
+ ...rest,
1357
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1358
+ });
1359
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1360
+ }
1361
+ /**
1362
+ * Deletes one or more messages from the thread
1363
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1364
+ * message object with id property, or array of message objects
1365
+ * @returns Promise containing deletion result
1366
+ */
1367
+ deleteMessages(messageIds) {
1368
+ const query = new URLSearchParams({
1369
+ agentId: this.agentId
1370
+ });
1371
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1372
+ method: "POST",
1373
+ body: { messageIds }
1374
+ });
1375
+ }
987
1376
  };
988
1377
 
989
1378
  // src/resources/vector.ts
@@ -1234,7 +1623,7 @@ var LegacyWorkflow = class extends BaseResource {
1234
1623
  };
1235
1624
 
1236
1625
  // src/resources/tool.ts
1237
- var Tool2 = class extends BaseResource {
1626
+ var Tool = class extends BaseResource {
1238
1627
  constructor(options, toolId) {
1239
1628
  super(options);
1240
1629
  this.toolId = toolId;
@@ -1405,6 +1794,14 @@ var Workflow = class extends BaseResource {
1405
1794
  method: "POST"
1406
1795
  });
1407
1796
  }
1797
+ /**
1798
+ * Creates a new workflow run (alias for createRun)
1799
+ * @param params - Optional object containing the optional runId
1800
+ * @returns Promise containing the runId of the created run
1801
+ */
1802
+ createRunAsync(params) {
1803
+ return this.createRun(params);
1804
+ }
1408
1805
  /**
1409
1806
  * Starts a workflow run synchronously without waiting for the workflow to complete
1410
1807
  * @param params - Object containing the runId, inputData and runtimeContext
@@ -1449,50 +1846,443 @@ var Workflow = class extends BaseResource {
1449
1846
  if (!!params?.runId) {
1450
1847
  searchParams.set("runId", params.runId);
1451
1848
  }
1452
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1453
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1454
- method: "POST",
1455
- body: { inputData: params.inputData, runtimeContext }
1456
- });
1849
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1850
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1851
+ method: "POST",
1852
+ body: { inputData: params.inputData, runtimeContext }
1853
+ });
1854
+ }
1855
+ /**
1856
+ * Starts a workflow run and returns a stream
1857
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1858
+ * @returns Promise containing the workflow execution results
1859
+ */
1860
+ async stream(params) {
1861
+ const searchParams = new URLSearchParams();
1862
+ if (!!params?.runId) {
1863
+ searchParams.set("runId", params.runId);
1864
+ }
1865
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1866
+ const response = await this.request(
1867
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1868
+ {
1869
+ method: "POST",
1870
+ body: { inputData: params.inputData, runtimeContext },
1871
+ stream: true
1872
+ }
1873
+ );
1874
+ if (!response.ok) {
1875
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1876
+ }
1877
+ if (!response.body) {
1878
+ throw new Error("Response body is null");
1879
+ }
1880
+ let failedChunk = void 0;
1881
+ const transformStream = new TransformStream({
1882
+ start() {
1883
+ },
1884
+ async transform(chunk, controller) {
1885
+ try {
1886
+ const decoded = new TextDecoder().decode(chunk);
1887
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1888
+ for (const chunk2 of chunks) {
1889
+ if (chunk2) {
1890
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1891
+ try {
1892
+ const parsedChunk = JSON.parse(newChunk);
1893
+ controller.enqueue(parsedChunk);
1894
+ failedChunk = void 0;
1895
+ } catch {
1896
+ failedChunk = newChunk;
1897
+ }
1898
+ }
1899
+ }
1900
+ } catch {
1901
+ }
1902
+ }
1903
+ });
1904
+ return response.body.pipeThrough(transformStream);
1905
+ }
1906
+ /**
1907
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1908
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1909
+ * @returns Promise containing the workflow resume results
1910
+ */
1911
+ resumeAsync(params) {
1912
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1913
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1914
+ method: "POST",
1915
+ body: {
1916
+ step: params.step,
1917
+ resumeData: params.resumeData,
1918
+ runtimeContext
1919
+ }
1920
+ });
1921
+ }
1922
+ /**
1923
+ * Watches workflow transitions in real-time
1924
+ * @param runId - Optional run ID to filter the watch stream
1925
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1926
+ */
1927
+ async watch({ runId }, onRecord) {
1928
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1929
+ stream: true
1930
+ });
1931
+ if (!response.ok) {
1932
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1933
+ }
1934
+ if (!response.body) {
1935
+ throw new Error("Response body is null");
1936
+ }
1937
+ for await (const record of this.streamProcessor(response.body)) {
1938
+ if (typeof record === "string") {
1939
+ onRecord(JSON.parse(record));
1940
+ } else {
1941
+ onRecord(record);
1942
+ }
1943
+ }
1944
+ }
1945
+ /**
1946
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1947
+ * serializing each as JSON and separating them with the record separator (\x1E).
1948
+ *
1949
+ * @param records - An iterable or async iterable of objects to stream
1950
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1951
+ */
1952
+ static createRecordStream(records) {
1953
+ const encoder = new TextEncoder();
1954
+ return new ReadableStream({
1955
+ async start(controller) {
1956
+ try {
1957
+ for await (const record of records) {
1958
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1959
+ controller.enqueue(encoder.encode(json));
1960
+ }
1961
+ controller.close();
1962
+ } catch (err) {
1963
+ controller.error(err);
1964
+ }
1965
+ }
1966
+ });
1967
+ }
1968
+ };
1969
+
1970
+ // src/resources/a2a.ts
1971
+ var A2A = class extends BaseResource {
1972
+ constructor(options, agentId) {
1973
+ super(options);
1974
+ this.agentId = agentId;
1975
+ }
1976
+ /**
1977
+ * Get the agent card with metadata about the agent
1978
+ * @returns Promise containing the agent card information
1979
+ */
1980
+ async getCard() {
1981
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1982
+ }
1983
+ /**
1984
+ * Send a message to the agent and gets a message or task response
1985
+ * @param params - Parameters for the task
1986
+ * @returns Promise containing the response
1987
+ */
1988
+ async sendMessage(params) {
1989
+ const response = await this.request(`/a2a/${this.agentId}`, {
1990
+ method: "POST",
1991
+ body: {
1992
+ method: "message/send",
1993
+ params
1994
+ }
1995
+ });
1996
+ return response;
1997
+ }
1998
+ /**
1999
+ * Sends a message to an agent to initiate/continue a task and subscribes
2000
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2001
+ * @param params - Parameters for the task
2002
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2003
+ */
2004
+ async sendStreamingMessage(params) {
2005
+ const response = await this.request(`/a2a/${this.agentId}`, {
2006
+ method: "POST",
2007
+ body: {
2008
+ method: "message/stream",
2009
+ params
2010
+ }
2011
+ });
2012
+ return response;
2013
+ }
2014
+ /**
2015
+ * Get the status and result of a task
2016
+ * @param params - Parameters for querying the task
2017
+ * @returns Promise containing the task response
2018
+ */
2019
+ async getTask(params) {
2020
+ const response = await this.request(`/a2a/${this.agentId}`, {
2021
+ method: "POST",
2022
+ body: {
2023
+ method: "tasks/get",
2024
+ params
2025
+ }
2026
+ });
2027
+ return response;
2028
+ }
2029
+ /**
2030
+ * Cancel a running task
2031
+ * @param params - Parameters identifying the task to cancel
2032
+ * @returns Promise containing the task response
2033
+ */
2034
+ async cancelTask(params) {
2035
+ return this.request(`/a2a/${this.agentId}`, {
2036
+ method: "POST",
2037
+ body: {
2038
+ method: "tasks/cancel",
2039
+ params
2040
+ }
2041
+ });
2042
+ }
2043
+ };
2044
+
2045
+ // src/resources/mcp-tool.ts
2046
+ var MCPTool = class extends BaseResource {
2047
+ serverId;
2048
+ toolId;
2049
+ constructor(options, serverId, toolId) {
2050
+ super(options);
2051
+ this.serverId = serverId;
2052
+ this.toolId = toolId;
2053
+ }
2054
+ /**
2055
+ * Retrieves details about this specific tool from the MCP server.
2056
+ * @returns Promise containing the tool's information (name, description, schema).
2057
+ */
2058
+ details() {
2059
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2060
+ }
2061
+ /**
2062
+ * Executes this specific tool on the MCP server.
2063
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2064
+ * @returns Promise containing the result of the tool execution.
2065
+ */
2066
+ execute(params) {
2067
+ const body = {};
2068
+ if (params.data !== void 0) body.data = params.data;
2069
+ if (params.runtimeContext !== void 0) {
2070
+ body.runtimeContext = params.runtimeContext;
2071
+ }
2072
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2073
+ method: "POST",
2074
+ body: Object.keys(body).length > 0 ? body : void 0
2075
+ });
2076
+ }
2077
+ };
2078
+
2079
+ // src/resources/agent-builder.ts
2080
+ var RECORD_SEPARATOR3 = "";
2081
+ var AgentBuilder = class extends BaseResource {
2082
+ constructor(options, actionId) {
2083
+ super(options);
2084
+ this.actionId = actionId;
2085
+ }
2086
+ // Helper function to transform workflow result to action result
2087
+ transformWorkflowResult(result) {
2088
+ if (result.status === "success") {
2089
+ return {
2090
+ success: result.result.success || false,
2091
+ applied: result.result.applied || false,
2092
+ branchName: result.result.branchName,
2093
+ message: result.result.message || "Agent builder action completed",
2094
+ validationResults: result.result.validationResults,
2095
+ error: result.result.error,
2096
+ errors: result.result.errors,
2097
+ stepResults: result.result.stepResults
2098
+ };
2099
+ } else if (result.status === "failed") {
2100
+ return {
2101
+ success: false,
2102
+ applied: false,
2103
+ message: `Agent builder action failed: ${result.error.message}`,
2104
+ error: result.error.message
2105
+ };
2106
+ } else {
2107
+ return {
2108
+ success: false,
2109
+ applied: false,
2110
+ message: "Agent builder action was suspended",
2111
+ error: "Workflow suspended - manual intervention required"
2112
+ };
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Creates a new agent builder action run and returns the runId.
2117
+ * This calls `/api/agent-builder/:actionId/create-run`.
2118
+ */
2119
+ async createRun(params) {
2120
+ const searchParams = new URLSearchParams();
2121
+ if (!!params?.runId) {
2122
+ searchParams.set("runId", params.runId);
2123
+ }
2124
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2125
+ return this.request(url, {
2126
+ method: "POST"
2127
+ });
2128
+ }
2129
+ /**
2130
+ * Creates a new workflow run (alias for createRun)
2131
+ * @param params - Optional object containing the optional runId
2132
+ * @returns Promise containing the runId of the created run
2133
+ */
2134
+ createRunAsync(params) {
2135
+ return this.createRun(params);
2136
+ }
2137
+ /**
2138
+ * Starts agent builder action asynchronously and waits for completion.
2139
+ * This calls `/api/agent-builder/:actionId/start-async`.
2140
+ */
2141
+ async startAsync(params, runId) {
2142
+ const searchParams = new URLSearchParams();
2143
+ if (runId) {
2144
+ searchParams.set("runId", runId);
2145
+ }
2146
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2147
+ const { runtimeContext: _, ...actionParams } = params;
2148
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2149
+ const result = await this.request(url, {
2150
+ method: "POST",
2151
+ body: { ...actionParams, runtimeContext }
2152
+ });
2153
+ return this.transformWorkflowResult(result);
2154
+ }
2155
+ /**
2156
+ * Starts an existing agent builder action run.
2157
+ * This calls `/api/agent-builder/:actionId/start`.
2158
+ */
2159
+ async startActionRun(params, runId) {
2160
+ const searchParams = new URLSearchParams();
2161
+ searchParams.set("runId", runId);
2162
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2163
+ const { runtimeContext: _, ...actionParams } = params;
2164
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2165
+ return this.request(url, {
2166
+ method: "POST",
2167
+ body: { ...actionParams, runtimeContext }
2168
+ });
2169
+ }
2170
+ /**
2171
+ * Resumes a suspended agent builder action step.
2172
+ * This calls `/api/agent-builder/:actionId/resume`.
2173
+ */
2174
+ async resume(params, runId) {
2175
+ const searchParams = new URLSearchParams();
2176
+ searchParams.set("runId", runId);
2177
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2178
+ const { runtimeContext: _, ...resumeParams } = params;
2179
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2180
+ return this.request(url, {
2181
+ method: "POST",
2182
+ body: { ...resumeParams, runtimeContext }
2183
+ });
2184
+ }
2185
+ /**
2186
+ * Resumes a suspended agent builder action step asynchronously.
2187
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2188
+ */
2189
+ async resumeAsync(params, runId) {
2190
+ const searchParams = new URLSearchParams();
2191
+ searchParams.set("runId", runId);
2192
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2193
+ const { runtimeContext: _, ...resumeParams } = params;
2194
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2195
+ const result = await this.request(url, {
2196
+ method: "POST",
2197
+ body: { ...resumeParams, runtimeContext }
2198
+ });
2199
+ return this.transformWorkflowResult(result);
2200
+ }
2201
+ /**
2202
+ * Creates an async generator that processes a readable stream and yields action records
2203
+ * separated by the Record Separator character (\x1E)
2204
+ *
2205
+ * @param stream - The readable stream to process
2206
+ * @returns An async generator that yields parsed records
2207
+ */
2208
+ async *streamProcessor(stream) {
2209
+ const reader = stream.getReader();
2210
+ let doneReading = false;
2211
+ let buffer = "";
2212
+ try {
2213
+ while (!doneReading) {
2214
+ const { done, value } = await reader.read();
2215
+ doneReading = done;
2216
+ if (done && !value) continue;
2217
+ try {
2218
+ const decoded = value ? new TextDecoder().decode(value) : "";
2219
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2220
+ buffer = chunks.pop() || "";
2221
+ for (const chunk of chunks) {
2222
+ if (chunk) {
2223
+ if (typeof chunk === "string") {
2224
+ try {
2225
+ const parsedChunk = JSON.parse(chunk);
2226
+ yield parsedChunk;
2227
+ } catch {
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ if (buffer) {
2236
+ try {
2237
+ yield JSON.parse(buffer);
2238
+ } catch {
2239
+ }
2240
+ }
2241
+ } finally {
2242
+ reader.cancel().catch(() => {
2243
+ });
2244
+ }
1457
2245
  }
1458
2246
  /**
1459
- * Starts a workflow run and returns a stream
1460
- * @param params - Object containing the optional runId, inputData and runtimeContext
1461
- * @returns Promise containing the workflow execution results
2247
+ * Streams agent builder action progress in real-time.
2248
+ * This calls `/api/agent-builder/:actionId/stream`.
1462
2249
  */
1463
- async stream(params) {
2250
+ async stream(params, runId) {
1464
2251
  const searchParams = new URLSearchParams();
1465
- if (!!params?.runId) {
1466
- searchParams.set("runId", params.runId);
2252
+ if (runId) {
2253
+ searchParams.set("runId", runId);
1467
2254
  }
1468
2255
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1469
- const response = await this.request(
1470
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1471
- {
1472
- method: "POST",
1473
- body: { inputData: params.inputData, runtimeContext },
1474
- stream: true
1475
- }
1476
- );
2256
+ const { runtimeContext: _, ...actionParams } = params;
2257
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2258
+ const response = await this.request(url, {
2259
+ method: "POST",
2260
+ body: { ...actionParams, runtimeContext },
2261
+ stream: true
2262
+ });
1477
2263
  if (!response.ok) {
1478
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2264
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1479
2265
  }
1480
2266
  if (!response.body) {
1481
2267
  throw new Error("Response body is null");
1482
2268
  }
2269
+ let failedChunk = void 0;
1483
2270
  const transformStream = new TransformStream({
1484
2271
  start() {
1485
2272
  },
1486
2273
  async transform(chunk, controller) {
1487
2274
  try {
1488
2275
  const decoded = new TextDecoder().decode(chunk);
1489
- const chunks = decoded.split(RECORD_SEPARATOR2);
2276
+ const chunks = decoded.split(RECORD_SEPARATOR3);
1490
2277
  for (const chunk2 of chunks) {
1491
2278
  if (chunk2) {
2279
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1492
2280
  try {
1493
- const parsedChunk = JSON.parse(chunk2);
2281
+ const parsedChunk = JSON.parse(newChunk);
1494
2282
  controller.enqueue(parsedChunk);
2283
+ failedChunk = void 0;
1495
2284
  } catch {
2285
+ failedChunk = newChunk;
1496
2286
  }
1497
2287
  }
1498
2288
  }
@@ -1503,32 +2293,68 @@ var Workflow = class extends BaseResource {
1503
2293
  return response.body.pipeThrough(transformStream);
1504
2294
  }
1505
2295
  /**
1506
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1507
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1508
- * @returns Promise containing the workflow resume results
2296
+ * Streams agent builder action progress in real-time using VNext streaming.
2297
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1509
2298
  */
1510
- resumeAsync(params) {
2299
+ async streamVNext(params, runId) {
2300
+ const searchParams = new URLSearchParams();
2301
+ if (runId) {
2302
+ searchParams.set("runId", runId);
2303
+ }
1511
2304
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1512
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2305
+ const { runtimeContext: _, ...actionParams } = params;
2306
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2307
+ const response = await this.request(url, {
1513
2308
  method: "POST",
1514
- body: {
1515
- step: params.step,
1516
- resumeData: params.resumeData,
1517
- runtimeContext
2309
+ body: { ...actionParams, runtimeContext },
2310
+ stream: true
2311
+ });
2312
+ if (!response.ok) {
2313
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2314
+ }
2315
+ if (!response.body) {
2316
+ throw new Error("Response body is null");
2317
+ }
2318
+ let failedChunk = void 0;
2319
+ const transformStream = new TransformStream({
2320
+ start() {
2321
+ },
2322
+ async transform(chunk, controller) {
2323
+ try {
2324
+ const decoded = new TextDecoder().decode(chunk);
2325
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2326
+ for (const chunk2 of chunks) {
2327
+ if (chunk2) {
2328
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2329
+ try {
2330
+ const parsedChunk = JSON.parse(newChunk);
2331
+ controller.enqueue(parsedChunk);
2332
+ failedChunk = void 0;
2333
+ } catch {
2334
+ failedChunk = newChunk;
2335
+ }
2336
+ }
2337
+ }
2338
+ } catch {
2339
+ }
1518
2340
  }
1519
2341
  });
2342
+ return response.body.pipeThrough(transformStream);
1520
2343
  }
1521
2344
  /**
1522
- * Watches workflow transitions in real-time
1523
- * @param runId - Optional run ID to filter the watch stream
1524
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2345
+ * Watches an existing agent builder action run by runId.
2346
+ * This is used for hot reload recovery - it loads the existing run state
2347
+ * and streams any remaining progress.
2348
+ * This calls `/api/agent-builder/:actionId/watch`.
1525
2349
  */
1526
- async watch({ runId }, onRecord) {
1527
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2350
+ async watch({ runId, eventType }, onRecord) {
2351
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2352
+ const response = await this.request(url, {
2353
+ method: "GET",
1528
2354
  stream: true
1529
2355
  });
1530
2356
  if (!response.ok) {
1531
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2357
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1532
2358
  }
1533
2359
  if (!response.body) {
1534
2360
  throw new Error("Response body is null");
@@ -1542,135 +2368,126 @@ var Workflow = class extends BaseResource {
1542
2368
  }
1543
2369
  }
1544
2370
  /**
1545
- * Creates a new ReadableStream from an iterable or async iterable of objects,
1546
- * serializing each as JSON and separating them with the record separator (\x1E).
1547
- *
1548
- * @param records - An iterable or async iterable of objects to stream
1549
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2371
+ * Gets a specific action run by its ID.
2372
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
1550
2373
  */
1551
- static createRecordStream(records) {
1552
- const encoder = new TextEncoder();
1553
- return new ReadableStream({
1554
- async start(controller) {
1555
- try {
1556
- for await (const record of records) {
1557
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1558
- controller.enqueue(encoder.encode(json));
1559
- }
1560
- controller.close();
1561
- } catch (err) {
1562
- controller.error(err);
1563
- }
1564
- }
2374
+ async runById(runId) {
2375
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2376
+ return this.request(url, {
2377
+ method: "GET"
1565
2378
  });
1566
2379
  }
1567
- };
1568
-
1569
- // src/resources/a2a.ts
1570
- var A2A = class extends BaseResource {
1571
- constructor(options, agentId) {
1572
- super(options);
1573
- this.agentId = agentId;
1574
- }
1575
2380
  /**
1576
- * Get the agent card with metadata about the agent
1577
- * @returns Promise containing the agent card information
2381
+ * Gets details about this agent builder action.
2382
+ * This calls `/api/agent-builder/:actionId`.
1578
2383
  */
1579
- async getCard() {
1580
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2384
+ async details() {
2385
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2386
+ return result;
1581
2387
  }
1582
2388
  /**
1583
- * Send a message to the agent and get a response
1584
- * @param params - Parameters for the task
1585
- * @returns Promise containing the task response
2389
+ * Gets all runs for this agent builder action.
2390
+ * This calls `/api/agent-builder/:actionId/runs`.
1586
2391
  */
1587
- async sendMessage(params) {
1588
- const response = await this.request(`/a2a/${this.agentId}`, {
1589
- method: "POST",
1590
- body: {
1591
- method: "tasks/send",
1592
- params
1593
- }
2392
+ async runs(params) {
2393
+ const searchParams = new URLSearchParams();
2394
+ if (params?.fromDate) {
2395
+ searchParams.set("fromDate", params.fromDate.toISOString());
2396
+ }
2397
+ if (params?.toDate) {
2398
+ searchParams.set("toDate", params.toDate.toISOString());
2399
+ }
2400
+ if (params?.limit !== void 0) {
2401
+ searchParams.set("limit", String(params.limit));
2402
+ }
2403
+ if (params?.offset !== void 0) {
2404
+ searchParams.set("offset", String(params.offset));
2405
+ }
2406
+ if (params?.resourceId) {
2407
+ searchParams.set("resourceId", params.resourceId);
2408
+ }
2409
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2410
+ return this.request(url, {
2411
+ method: "GET"
1594
2412
  });
1595
- return { task: response.result };
1596
2413
  }
1597
2414
  /**
1598
- * Get the status and result of a task
1599
- * @param params - Parameters for querying the task
1600
- * @returns Promise containing the task response
2415
+ * Gets the execution result of an agent builder action run.
2416
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1601
2417
  */
1602
- async getTask(params) {
1603
- const response = await this.request(`/a2a/${this.agentId}`, {
1604
- method: "POST",
1605
- body: {
1606
- method: "tasks/get",
1607
- params
1608
- }
2418
+ async runExecutionResult(runId) {
2419
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2420
+ return this.request(url, {
2421
+ method: "GET"
1609
2422
  });
1610
- return response.result;
1611
2423
  }
1612
2424
  /**
1613
- * Cancel a running task
1614
- * @param params - Parameters identifying the task to cancel
1615
- * @returns Promise containing the task response
2425
+ * Cancels an agent builder action run.
2426
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1616
2427
  */
1617
- async cancelTask(params) {
1618
- return this.request(`/a2a/${this.agentId}`, {
1619
- method: "POST",
1620
- body: {
1621
- method: "tasks/cancel",
1622
- params
1623
- }
2428
+ async cancelRun(runId) {
2429
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2430
+ return this.request(url, {
2431
+ method: "POST"
1624
2432
  });
1625
2433
  }
1626
2434
  /**
1627
- * Send a message and subscribe to streaming updates (not fully implemented)
1628
- * @param params - Parameters for the task
1629
- * @returns Promise containing the task response
2435
+ * Sends an event to an agent builder action run.
2436
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1630
2437
  */
1631
- async sendAndSubscribe(params) {
1632
- return this.request(`/a2a/${this.agentId}`, {
2438
+ async sendRunEvent(params) {
2439
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2440
+ return this.request(url, {
1633
2441
  method: "POST",
1634
- body: {
1635
- method: "tasks/sendSubscribe",
1636
- params
1637
- },
1638
- stream: true
2442
+ body: { event: params.event, data: params.data }
1639
2443
  });
1640
2444
  }
1641
2445
  };
1642
2446
 
1643
- // src/resources/mcp-tool.ts
1644
- var MCPTool = class extends BaseResource {
1645
- serverId;
1646
- toolId;
1647
- constructor(options, serverId, toolId) {
2447
+ // src/resources/observability.ts
2448
+ var Observability = class extends BaseResource {
2449
+ constructor(options) {
1648
2450
  super(options);
1649
- this.serverId = serverId;
1650
- this.toolId = toolId;
1651
2451
  }
1652
2452
  /**
1653
- * Retrieves details about this specific tool from the MCP server.
1654
- * @returns Promise containing the tool's information (name, description, schema).
2453
+ * Retrieves a specific AI trace by ID
2454
+ * @param traceId - ID of the trace to retrieve
2455
+ * @returns Promise containing the AI trace with all its spans
1655
2456
  */
1656
- details() {
1657
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2457
+ getTrace(traceId) {
2458
+ return this.request(`/api/observability/traces/${traceId}`);
1658
2459
  }
1659
2460
  /**
1660
- * Executes this specific tool on the MCP server.
1661
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1662
- * @returns Promise containing the result of the tool execution.
2461
+ * Retrieves paginated list of AI traces with optional filtering
2462
+ * @param params - Parameters for pagination and filtering
2463
+ * @returns Promise containing paginated traces and pagination info
1663
2464
  */
1664
- execute(params) {
1665
- const body = {};
1666
- if (params.data !== void 0) body.data = params.data;
1667
- if (params.runtimeContext !== void 0) {
1668
- body.runtimeContext = params.runtimeContext;
2465
+ getTraces(params) {
2466
+ const { pagination, filters } = params;
2467
+ const { page, perPage, dateRange } = pagination || {};
2468
+ const { name, spanType } = filters || {};
2469
+ const searchParams = new URLSearchParams();
2470
+ if (page !== void 0) {
2471
+ searchParams.set("page", String(page));
1669
2472
  }
1670
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1671
- method: "POST",
1672
- body: Object.keys(body).length > 0 ? body : void 0
1673
- });
2473
+ if (perPage !== void 0) {
2474
+ searchParams.set("perPage", String(perPage));
2475
+ }
2476
+ if (name) {
2477
+ searchParams.set("name", name);
2478
+ }
2479
+ if (spanType !== void 0) {
2480
+ searchParams.set("spanType", String(spanType));
2481
+ }
2482
+ if (dateRange) {
2483
+ const dateRangeStr = JSON.stringify({
2484
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2485
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2486
+ });
2487
+ searchParams.set("dateRange", dateRangeStr);
2488
+ }
2489
+ const queryString = searchParams.toString();
2490
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
1674
2491
  }
1675
2492
  };
1676
2493
 
@@ -1720,10 +2537,25 @@ var NetworkMemoryThread = class extends BaseResource {
1720
2537
  });
1721
2538
  return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1722
2539
  }
2540
+ /**
2541
+ * Deletes one or more messages from the thread
2542
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2543
+ * message object with id property, or array of message objects
2544
+ * @returns Promise containing deletion result
2545
+ */
2546
+ deleteMessages(messageIds) {
2547
+ const query = new URLSearchParams({
2548
+ networkId: this.networkId
2549
+ });
2550
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2551
+ method: "POST",
2552
+ body: { messageIds }
2553
+ });
2554
+ }
1723
2555
  };
1724
2556
 
1725
2557
  // src/resources/vNextNetwork.ts
1726
- var RECORD_SEPARATOR3 = "";
2558
+ var RECORD_SEPARATOR4 = "";
1727
2559
  var VNextNetwork = class extends BaseResource {
1728
2560
  constructor(options, networkId) {
1729
2561
  super(options);
@@ -1775,7 +2607,7 @@ var VNextNetwork = class extends BaseResource {
1775
2607
  if (done && !value) continue;
1776
2608
  try {
1777
2609
  const decoded = value ? new TextDecoder().decode(value) : "";
1778
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2610
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
1779
2611
  buffer = chunks.pop() || "";
1780
2612
  for (const chunk of chunks) {
1781
2613
  if (chunk) {
@@ -1862,8 +2694,10 @@ var VNextNetwork = class extends BaseResource {
1862
2694
 
1863
2695
  // src/client.ts
1864
2696
  var MastraClient = class extends BaseResource {
2697
+ observability;
1865
2698
  constructor(options) {
1866
2699
  super(options);
2700
+ this.observability = new Observability(options);
1867
2701
  }
1868
2702
  /**
1869
2703
  * Retrieves all available agents
@@ -1872,21 +2706,6 @@ var MastraClient = class extends BaseResource {
1872
2706
  getAgents() {
1873
2707
  return this.request("/api/agents");
1874
2708
  }
1875
- async getAGUI({ resourceId }) {
1876
- const agents = await this.getAgents();
1877
- return Object.entries(agents).reduce(
1878
- (acc, [agentId]) => {
1879
- const agent = this.getAgent(agentId);
1880
- acc[agentId] = new AGUIAdapter({
1881
- agentId,
1882
- agent,
1883
- resourceId
1884
- });
1885
- return acc;
1886
- },
1887
- {}
1888
- );
1889
- }
1890
2709
  /**
1891
2710
  * Gets an agent instance by ID
1892
2711
  * @param agentId - ID of the agent to retrieve
@@ -1992,7 +2811,7 @@ var MastraClient = class extends BaseResource {
1992
2811
  * @returns Tool instance
1993
2812
  */
1994
2813
  getTool(toolId) {
1995
- return new Tool2(this.options, toolId);
2814
+ return new Tool(this.options, toolId);
1996
2815
  }
1997
2816
  /**
1998
2817
  * Retrieves all available legacy workflows
@@ -2024,6 +2843,20 @@ var MastraClient = class extends BaseResource {
2024
2843
  getWorkflow(workflowId) {
2025
2844
  return new Workflow(this.options, workflowId);
2026
2845
  }
2846
+ /**
2847
+ * Gets all available agent builder actions
2848
+ * @returns Promise containing map of action IDs to action details
2849
+ */
2850
+ getAgentBuilderActions() {
2851
+ return this.request("/api/agent-builder/");
2852
+ }
2853
+ /**
2854
+ * Gets an agent builder instance for executing agent-builder workflows
2855
+ * @returns AgentBuilder instance
2856
+ */
2857
+ getAgentBuilderAction(actionId) {
2858
+ return new AgentBuilder(this.options, actionId);
2859
+ }
2027
2860
  /**
2028
2861
  * Gets a vector instance by name
2029
2862
  * @param vectorName - Name of the vector to retrieve
@@ -2289,6 +3122,99 @@ var MastraClient = class extends BaseResource {
2289
3122
  }
2290
3123
  });
2291
3124
  }
3125
+ /**
3126
+ * Retrieves all available scorers
3127
+ * @returns Promise containing list of available scorers
3128
+ */
3129
+ getScorers() {
3130
+ return this.request("/api/scores/scorers");
3131
+ }
3132
+ /**
3133
+ * Retrieves a scorer by ID
3134
+ * @param scorerId - ID of the scorer to retrieve
3135
+ * @returns Promise containing the scorer
3136
+ */
3137
+ getScorer(scorerId) {
3138
+ return this.request(`/api/scores/scorers/${scorerId}`);
3139
+ }
3140
+ getScoresByScorerId(params) {
3141
+ const { page, perPage, scorerId, entityId, entityType } = params;
3142
+ const searchParams = new URLSearchParams();
3143
+ if (entityId) {
3144
+ searchParams.set("entityId", entityId);
3145
+ }
3146
+ if (entityType) {
3147
+ searchParams.set("entityType", entityType);
3148
+ }
3149
+ if (page !== void 0) {
3150
+ searchParams.set("page", String(page));
3151
+ }
3152
+ if (perPage !== void 0) {
3153
+ searchParams.set("perPage", String(perPage));
3154
+ }
3155
+ const queryString = searchParams.toString();
3156
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3157
+ }
3158
+ /**
3159
+ * Retrieves scores by run ID
3160
+ * @param params - Parameters containing run ID and pagination options
3161
+ * @returns Promise containing scores and pagination info
3162
+ */
3163
+ getScoresByRunId(params) {
3164
+ const { runId, page, perPage } = params;
3165
+ const searchParams = new URLSearchParams();
3166
+ if (page !== void 0) {
3167
+ searchParams.set("page", String(page));
3168
+ }
3169
+ if (perPage !== void 0) {
3170
+ searchParams.set("perPage", String(perPage));
3171
+ }
3172
+ const queryString = searchParams.toString();
3173
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3174
+ }
3175
+ /**
3176
+ * Retrieves scores by entity ID and type
3177
+ * @param params - Parameters containing entity ID, type, and pagination options
3178
+ * @returns Promise containing scores and pagination info
3179
+ */
3180
+ getScoresByEntityId(params) {
3181
+ const { entityId, entityType, page, perPage } = params;
3182
+ const searchParams = new URLSearchParams();
3183
+ if (page !== void 0) {
3184
+ searchParams.set("page", String(page));
3185
+ }
3186
+ if (perPage !== void 0) {
3187
+ searchParams.set("perPage", String(perPage));
3188
+ }
3189
+ const queryString = searchParams.toString();
3190
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3191
+ }
3192
+ /**
3193
+ * Saves a score
3194
+ * @param params - Parameters containing the score data to save
3195
+ * @returns Promise containing the saved score
3196
+ */
3197
+ saveScore(params) {
3198
+ return this.request("/api/scores", {
3199
+ method: "POST",
3200
+ body: params
3201
+ });
3202
+ }
3203
+ /**
3204
+ * Retrieves model providers with available keys
3205
+ * @returns Promise containing model providers with available keys
3206
+ */
3207
+ getModelProviders() {
3208
+ return this.request(`/api/model-providers`);
3209
+ }
3210
+ getAITrace(traceId) {
3211
+ return this.observability.getTrace(traceId);
3212
+ }
3213
+ getAITraces(params) {
3214
+ return this.observability.getTraces(params);
3215
+ }
2292
3216
  };
2293
3217
 
2294
3218
  exports.MastraClient = MastraClient;
3219
+ //# sourceMappingURL=index.cjs.map
3220
+ //# sourceMappingURL=index.cjs.map