@mastra/client-js 0.0.0-ai-v5-20250813235735 → 0.0.0-ai-telementry-ui-20250908100313

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 (73) hide show
  1. package/CHANGELOG.md +400 -4
  2. package/README.md +5 -3
  3. package/dist/client.d.ts +16 -6
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +1170 -407
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1169 -406
  10. package/dist/index.js.map +1 -1
  11. package/dist/resources/agent-builder.d.ts +161 -0
  12. package/dist/resources/agent-builder.d.ts.map +1 -0
  13. package/dist/resources/agent.d.ts +44 -12
  14. package/dist/resources/agent.d.ts.map +1 -1
  15. package/dist/resources/index.d.ts +2 -0
  16. package/dist/resources/index.d.ts.map +1 -1
  17. package/dist/resources/memory-thread.d.ts +1 -1
  18. package/dist/resources/memory-thread.d.ts.map +1 -1
  19. package/dist/resources/network-memory-thread.d.ts +1 -1
  20. package/dist/resources/network-memory-thread.d.ts.map +1 -1
  21. package/dist/resources/network.d.ts +2 -2
  22. package/dist/resources/network.d.ts.map +1 -1
  23. package/dist/resources/observability.d.ts +19 -0
  24. package/dist/resources/observability.d.ts.map +1 -0
  25. package/dist/resources/tool.d.ts.map +1 -1
  26. package/dist/resources/vNextNetwork.d.ts +1 -1
  27. package/dist/resources/vNextNetwork.d.ts.map +1 -1
  28. package/dist/types.d.ts +44 -10
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/utils/process-client-tools.d.ts.map +1 -1
  31. package/dist/utils/process-mastra-stream.d.ts +7 -0
  32. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  33. package/dist/utils/zod-to-json-schema.d.ts +2 -104
  34. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  35. package/package.json +24 -16
  36. package/.turbo/turbo-build.log +0 -18
  37. package/dist/adapters/agui.d.ts +0 -22
  38. package/dist/adapters/agui.d.ts.map +0 -1
  39. package/eslint.config.js +0 -6
  40. package/integration-tests/agui-adapter.test.ts +0 -122
  41. package/integration-tests/package.json +0 -17
  42. package/integration-tests/src/mastra/index.ts +0 -38
  43. package/integration-tests/vitest.config.ts +0 -9
  44. package/src/adapters/agui.test.ts +0 -322
  45. package/src/adapters/agui.ts +0 -263
  46. package/src/client.ts +0 -631
  47. package/src/example.ts +0 -95
  48. package/src/index.test.ts +0 -1226
  49. package/src/index.ts +0 -2
  50. package/src/resources/a2a.ts +0 -98
  51. package/src/resources/agent.ts +0 -793
  52. package/src/resources/base.ts +0 -77
  53. package/src/resources/index.ts +0 -10
  54. package/src/resources/legacy-workflow.ts +0 -242
  55. package/src/resources/mcp-tool.ts +0 -48
  56. package/src/resources/memory-thread.test.ts +0 -285
  57. package/src/resources/memory-thread.ts +0 -100
  58. package/src/resources/network-memory-thread.test.ts +0 -269
  59. package/src/resources/network-memory-thread.ts +0 -81
  60. package/src/resources/network.ts +0 -86
  61. package/src/resources/tool.ts +0 -45
  62. package/src/resources/vNextNetwork.ts +0 -194
  63. package/src/resources/vector.ts +0 -83
  64. package/src/resources/workflow.ts +0 -410
  65. package/src/types.ts +0 -506
  66. package/src/utils/index.ts +0 -11
  67. package/src/utils/process-client-tools.ts +0 -32
  68. package/src/utils/zod-to-json-schema.ts +0 -10
  69. package/src/v2-messages.test.ts +0 -180
  70. package/tsconfig.build.json +0 -9
  71. package/tsconfig.json +0 -5
  72. package/tsup.config.ts +0 -17
  73. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,226 +1,41 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
- var ai = require('ai');
6
- var zod = require('zod');
7
- var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
3
+ var uiUtils = require('@ai-sdk/ui-utils');
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
- const toolCallsWithResults = /* @__PURE__ */ new Set();
155
- for (const message of messages) {
156
- if (message.role === "tool" && message.toolCallId) {
157
- toolCallsWithResults.add(message.toolCallId);
158
- }
159
- }
160
- for (const message of messages) {
161
- if (message.role === "assistant") {
162
- const content = [];
163
- if (message.content) {
164
- content.push({ type: "text", text: message.content });
165
- }
166
- for (const toolCall of message.toolCalls ?? []) {
167
- content.push({
168
- type: "tool-call",
169
- toolCallId: toolCall.id,
170
- toolName: toolCall.function.name,
171
- args: JSON.parse(toolCall.function.arguments)
172
- });
173
- }
174
- result.push({
175
- role: "assistant",
176
- content: content.length > 0 ? content : message.content || ""
177
- });
178
- if (message.toolCalls?.length) {
179
- for (const toolCall of message.toolCalls) {
180
- if (!toolCallsWithResults.has(toolCall.id)) {
181
- result.push({
182
- role: "tool",
183
- content: [
184
- {
185
- type: "tool-result",
186
- toolCallId: toolCall.id,
187
- toolName: toolCall.function.name,
188
- result: JSON.parse(toolCall.function.arguments)
189
- // This is still wrong but matches test expectations
190
- }
191
- ]
192
- });
193
- }
194
- }
195
- }
196
- } else if (message.role === "user") {
197
- result.push({
198
- role: "user",
199
- content: message.content || ""
200
- });
201
- } else if (message.role === "tool") {
202
- result.push({
203
- role: "tool",
204
- content: [
205
- {
206
- type: "tool-result",
207
- toolCallId: message.toolCallId || "unknown",
208
- toolName: "unknown",
209
- // toolName is not available in tool messages from CopilotKit
210
- result: message.content
211
- }
212
- ]
213
- });
214
- }
215
- }
216
- 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";
217
26
  }
218
27
  function zodToJsonSchema(zodSchema) {
219
- if (!(zodSchema instanceof zod.ZodSchema)) {
28
+ if (!isZodType(zodSchema)) {
220
29
  return zodSchema;
221
30
  }
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
222
35
  return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
223
36
  }
37
+
38
+ // src/utils/process-client-tools.ts
224
39
  function processClientTools(clientTools) {
225
40
  if (!clientTools) {
226
41
  return void 0;
@@ -232,7 +47,7 @@ function processClientTools(clientTools) {
232
47
  key,
233
48
  {
234
49
  ...value,
235
- inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0
50
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
236
51
  }
237
52
  ];
238
53
  } else {
@@ -249,6 +64,42 @@ function processClientTools(clientTools) {
249
64
  );
250
65
  }
251
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
+
252
103
  // src/resources/base.ts
253
104
  var BaseResource = class {
254
105
  options;
@@ -263,7 +114,7 @@ var BaseResource = class {
263
114
  */
264
115
  async request(path, options = {}) {
265
116
  let lastError = null;
266
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
267
118
  let delay = backoffMs;
268
119
  for (let attempt = 0; attempt <= retries; attempt++) {
269
120
  try {
@@ -272,12 +123,12 @@ var BaseResource = class {
272
123
  headers: {
273
124
  ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
274
125
  ...headers,
275
- ...options.headers,
126
+ ...options.headers
276
127
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
277
128
  // 'x-mastra-client-type': 'js',
278
- "x-ai-sdk-compat": "v4"
279
129
  },
280
130
  signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
281
132
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
282
133
  });
283
134
  if (!response.ok) {
@@ -310,14 +161,64 @@ var BaseResource = class {
310
161
  throw lastError || new Error("Request failed");
311
162
  }
312
163
  };
313
- function parseClientRuntimeContext(runtimeContext$1) {
314
- if (runtimeContext$1) {
315
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
316
- 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
+ }
317
220
  }
318
- return runtimeContext$1;
319
221
  }
320
- return void 0;
321
222
  }
322
223
  var AgentVoice = class extends BaseResource {
323
224
  constructor(options, agentId) {
@@ -388,6 +289,12 @@ var Agent = class extends BaseResource {
388
289
  return this.request(`/api/agents/${this.agentId}`);
389
290
  }
390
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) {
391
298
  const processedParams = {
392
299
  ...params,
393
300
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -397,7 +304,7 @@ var Agent = class extends BaseResource {
397
304
  };
398
305
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
399
306
  const response = await this.request(
400
- `/api/agents/${this.agentId}/generate`,
307
+ `/api/agents/${this.agentId}/generate-legacy`,
401
308
  {
402
309
  method: "POST",
403
310
  body: processedParams
@@ -412,7 +319,14 @@ var Agent = class extends BaseResource {
412
319
  const clientTool = params.clientTools?.[toolCall.toolName];
413
320
  if (clientTool && clientTool.execute) {
414
321
  const result = await clientTool.execute(
415
- { 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
+ },
416
330
  {
417
331
  messages: response.messages,
418
332
  toolCallId: toolCall?.toolCallId
@@ -445,6 +359,34 @@ var Agent = class extends BaseResource {
445
359
  }
446
360
  return response;
447
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
+ }
448
390
  async processChatResponse({
449
391
  stream,
450
392
  update,
@@ -512,7 +454,7 @@ var Agent = class extends BaseResource {
512
454
  replaceLastMessage
513
455
  });
514
456
  }
515
- await ai.processDataStream({
457
+ await uiUtils.processDataStream({
516
458
  stream,
517
459
  onTextPart(value) {
518
460
  if (currentTextPart == null) {
@@ -609,12 +551,7 @@ var Agent = class extends BaseResource {
609
551
  onToolCallDeltaPart(value) {
610
552
  const partialToolCall = partialToolCalls[value.toolCallId];
611
553
  partialToolCall.text += value.argsTextDelta;
612
- let partialArgs;
613
- try {
614
- partialArgs = JSON.parse(partialToolCall.text);
615
- } catch {
616
- partialArgs = void 0;
617
- }
554
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
618
555
  const invocation = {
619
556
  state: "partial-call",
620
557
  step: partialToolCall.step,
@@ -718,6 +655,17 @@ var Agent = class extends BaseResource {
718
655
  * @returns Promise containing the enhanced Response object with processDataStream method
719
656
  */
720
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) {
721
669
  const processedParams = {
722
670
  ...params,
723
671
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -733,18 +681,268 @@ var Agent = class extends BaseResource {
733
681
  headers: response.headers
734
682
  });
735
683
  streamResponse.processDataStream = async (options = {}) => {
736
- await ai.processDataStream({
684
+ await uiUtils.processDataStream({
737
685
  stream: streamResponse.body,
738
686
  ...options
739
687
  });
740
688
  };
741
689
  return streamResponse;
742
690
  }
743
- /**
744
- * Processes the stream response and handles tool calls
745
- */
746
- async processStreamResponse(processedParams, writable) {
747
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
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`, {
748
946
  method: "POST",
749
947
  body: processedParams,
750
948
  stream: true
@@ -761,7 +959,7 @@ var Agent = class extends BaseResource {
761
959
  }).catch((error) => {
762
960
  console.error("Error piping to writable stream:", error);
763
961
  });
764
- this.processChatResponse({
962
+ this.processChatResponse_vNext({
765
963
  stream: streamForProcessing,
766
964
  update: ({ message }) => {
767
965
  const existingIndex = messages.findIndex((m) => m.id === message.id);
@@ -786,7 +984,9 @@ var Agent = class extends BaseResource {
786
984
  runId: processedParams.runId,
787
985
  resourceId: processedParams.resourceId,
788
986
  threadId: processedParams.threadId,
789
- runtimeContext: processedParams.runtimeContext
987
+ runtimeContext: processedParams.runtimeContext,
988
+ // TODO: Pass proper tracing context when client-js supports tracing
989
+ tracingContext: { currentSpan: void 0 }
790
990
  },
791
991
  {
792
992
  messages: response.messages,
@@ -826,7 +1026,7 @@ var Agent = class extends BaseResource {
826
1026
  }
827
1027
  const originalMessages = processedParams.messages;
828
1028
  const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
829
- this.processStreamResponse(
1029
+ this.processStreamResponse_vNext(
830
1030
  {
831
1031
  ...processedParams,
832
1032
  messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
@@ -852,14 +1052,152 @@ var Agent = class extends BaseResource {
852
1052
  }
853
1053
  return response;
854
1054
  }
855
- /**
856
- * Gets details about a specific tool available to the agent
857
- * @param toolId - ID of the tool to retrieve
858
- * @returns Promise containing tool details
859
- */
860
- getTool(toolId) {
861
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
862
- }
1055
+ async streamVNext(params) {
1056
+ const processedParams = {
1057
+ ...params,
1058
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1059
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1060
+ clientTools: processClientTools(params.clientTools)
1061
+ };
1062
+ const { readable, writable } = new TransformStream();
1063
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1064
+ const streamResponse = new Response(readable, {
1065
+ status: response.status,
1066
+ statusText: response.statusText,
1067
+ headers: response.headers
1068
+ });
1069
+ streamResponse.processDataStream = async ({
1070
+ onChunk
1071
+ }) => {
1072
+ await processMastraStream({
1073
+ stream: streamResponse.body,
1074
+ onChunk
1075
+ });
1076
+ };
1077
+ return streamResponse;
1078
+ }
1079
+ /**
1080
+ * Processes the stream response and handles tool calls
1081
+ */
1082
+ async processStreamResponse(processedParams, writable) {
1083
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1084
+ method: "POST",
1085
+ body: processedParams,
1086
+ stream: true
1087
+ });
1088
+ if (!response.body) {
1089
+ throw new Error("No response body");
1090
+ }
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);
1099
+ });
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
+ }
863
1201
  /**
864
1202
  * Executes a tool for the agent
865
1203
  * @param toolId - ID of the tool to execute
@@ -950,7 +1288,7 @@ var Network = class extends BaseResource {
950
1288
  throw new Error("No response body");
951
1289
  }
952
1290
  response.processDataStream = async (options = {}) => {
953
- await ai.processDataStream({
1291
+ await uiUtils.processDataStream({
954
1292
  stream: response.body,
955
1293
  ...options
956
1294
  });
@@ -1001,8 +1339,7 @@ var MemoryThread = class extends BaseResource {
1001
1339
  getMessages(params) {
1002
1340
  const query = new URLSearchParams({
1003
1341
  agentId: this.agentId,
1004
- ...params?.limit ? { limit: params.limit.toString() } : {},
1005
- ...params?.format ? { format: params.format } : {}
1342
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1006
1343
  });
1007
1344
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
1008
1345
  }
@@ -1286,7 +1623,7 @@ var LegacyWorkflow = class extends BaseResource {
1286
1623
  };
1287
1624
 
1288
1625
  // src/resources/tool.ts
1289
- var Tool2 = class extends BaseResource {
1626
+ var Tool = class extends BaseResource {
1290
1627
  constructor(options, toolId) {
1291
1628
  super(options);
1292
1629
  this.toolId = toolId;
@@ -1497,45 +1834,434 @@ var Workflow = class extends BaseResource {
1497
1834
  resumeData,
1498
1835
  runtimeContext
1499
1836
  }
1500
- });
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1841
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1842
+ * @returns Promise containing the workflow execution results
1843
+ */
1844
+ startAsync(params) {
1845
+ const searchParams = new URLSearchParams();
1846
+ if (!!params?.runId) {
1847
+ searchParams.set("runId", params.runId);
1848
+ }
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
+ }
1501
2245
  }
1502
2246
  /**
1503
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1504
- * @param params - Object containing the optional runId, inputData and runtimeContext
1505
- * @returns Promise containing the workflow execution results
2247
+ * Streams agent builder action progress in real-time.
2248
+ * This calls `/api/agent-builder/:actionId/stream`.
1506
2249
  */
1507
- startAsync(params) {
2250
+ async stream(params, runId) {
1508
2251
  const searchParams = new URLSearchParams();
1509
- if (!!params?.runId) {
1510
- searchParams.set("runId", params.runId);
2252
+ if (runId) {
2253
+ searchParams.set("runId", runId);
1511
2254
  }
1512
2255
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1513
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
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, {
1514
2259
  method: "POST",
1515
- body: { inputData: params.inputData, runtimeContext }
2260
+ body: { ...actionParams, runtimeContext },
2261
+ stream: true
1516
2262
  });
1517
- }
1518
- /**
1519
- * Starts a workflow run and returns a stream
1520
- * @param params - Object containing the optional runId, inputData and runtimeContext
1521
- * @returns Promise containing the workflow execution results
1522
- */
1523
- async stream(params) {
1524
- const searchParams = new URLSearchParams();
1525
- if (!!params?.runId) {
1526
- searchParams.set("runId", params.runId);
1527
- }
1528
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1529
- const response = await this.request(
1530
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1531
- {
1532
- method: "POST",
1533
- body: { inputData: params.inputData, runtimeContext },
1534
- stream: true
1535
- }
1536
- );
1537
2263
  if (!response.ok) {
1538
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2264
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1539
2265
  }
1540
2266
  if (!response.body) {
1541
2267
  throw new Error("Response body is null");
@@ -1547,7 +2273,7 @@ var Workflow = class extends BaseResource {
1547
2273
  async transform(chunk, controller) {
1548
2274
  try {
1549
2275
  const decoded = new TextDecoder().decode(chunk);
1550
- const chunks = decoded.split(RECORD_SEPARATOR2);
2276
+ const chunks = decoded.split(RECORD_SEPARATOR3);
1551
2277
  for (const chunk2 of chunks) {
1552
2278
  if (chunk2) {
1553
2279
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1555,7 +2281,7 @@ var Workflow = class extends BaseResource {
1555
2281
  const parsedChunk = JSON.parse(newChunk);
1556
2282
  controller.enqueue(parsedChunk);
1557
2283
  failedChunk = void 0;
1558
- } catch (error) {
2284
+ } catch {
1559
2285
  failedChunk = newChunk;
1560
2286
  }
1561
2287
  }
@@ -1567,32 +2293,68 @@ var Workflow = class extends BaseResource {
1567
2293
  return response.body.pipeThrough(transformStream);
1568
2294
  }
1569
2295
  /**
1570
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1571
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1572
- * @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`.
1573
2298
  */
1574
- resumeAsync(params) {
2299
+ async streamVNext(params, runId) {
2300
+ const searchParams = new URLSearchParams();
2301
+ if (runId) {
2302
+ searchParams.set("runId", runId);
2303
+ }
1575
2304
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1576
- 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, {
1577
2308
  method: "POST",
1578
- body: {
1579
- step: params.step,
1580
- resumeData: params.resumeData,
1581
- 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
+ }
1582
2340
  }
1583
2341
  });
2342
+ return response.body.pipeThrough(transformStream);
1584
2343
  }
1585
2344
  /**
1586
- * Watches workflow transitions in real-time
1587
- * @param runId - Optional run ID to filter the watch stream
1588
- * @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`.
1589
2349
  */
1590
- async watch({ runId }, onRecord) {
1591
- 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",
1592
2354
  stream: true
1593
2355
  });
1594
2356
  if (!response.ok) {
1595
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2357
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1596
2358
  }
1597
2359
  if (!response.body) {
1598
2360
  throw new Error("Response body is null");
@@ -1606,136 +2368,130 @@ var Workflow = class extends BaseResource {
1606
2368
  }
1607
2369
  }
1608
2370
  /**
1609
- * Creates a new ReadableStream from an iterable or async iterable of objects,
1610
- * serializing each as JSON and separating them with the record separator (\x1E).
1611
- *
1612
- * @param records - An iterable or async iterable of objects to stream
1613
- * @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`.
1614
2373
  */
1615
- static createRecordStream(records) {
1616
- const encoder = new TextEncoder();
1617
- return new ReadableStream({
1618
- async start(controller) {
1619
- try {
1620
- for await (const record of records) {
1621
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1622
- controller.enqueue(encoder.encode(json));
1623
- }
1624
- controller.close();
1625
- } catch (err) {
1626
- controller.error(err);
1627
- }
1628
- }
2374
+ async runById(runId) {
2375
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2376
+ return this.request(url, {
2377
+ method: "GET"
1629
2378
  });
1630
2379
  }
1631
- };
1632
-
1633
- // src/resources/a2a.ts
1634
- var A2A = class extends BaseResource {
1635
- constructor(options, agentId) {
1636
- super(options);
1637
- this.agentId = agentId;
1638
- }
1639
2380
  /**
1640
- * Get the agent card with metadata about the agent
1641
- * @returns Promise containing the agent card information
2381
+ * Gets details about this agent builder action.
2382
+ * This calls `/api/agent-builder/:actionId`.
1642
2383
  */
1643
- async getCard() {
1644
- return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2384
+ async details() {
2385
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2386
+ return result;
1645
2387
  }
1646
2388
  /**
1647
- * Send a message to the agent and gets a message or task response
1648
- * @param params - Parameters for the task
1649
- * @returns Promise containing the response
2389
+ * Gets all runs for this agent builder action.
2390
+ * This calls `/api/agent-builder/:actionId/runs`.
1650
2391
  */
1651
- async sendMessage(params) {
1652
- const response = await this.request(`/a2a/${this.agentId}`, {
1653
- method: "POST",
1654
- body: {
1655
- method: "message/send",
1656
- params
1657
- }
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"
1658
2412
  });
1659
- return response;
1660
2413
  }
1661
2414
  /**
1662
- * Sends a message to an agent to initiate/continue a task and subscribes
1663
- * the client to real-time updates for that task via Server-Sent Events (SSE).
1664
- * @param params - Parameters for the task
1665
- * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2415
+ * Gets the execution result of an agent builder action run.
2416
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1666
2417
  */
1667
- async sendStreamingMessage(params) {
1668
- const response = await this.request(`/a2a/${this.agentId}`, {
1669
- method: "POST",
1670
- body: {
1671
- method: "message/stream",
1672
- params
1673
- }
2418
+ async runExecutionResult(runId) {
2419
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2420
+ return this.request(url, {
2421
+ method: "GET"
1674
2422
  });
1675
- return response;
1676
2423
  }
1677
2424
  /**
1678
- * Get the status and result of a task
1679
- * @param params - Parameters for querying the task
1680
- * @returns Promise containing the task response
2425
+ * Cancels an agent builder action run.
2426
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1681
2427
  */
1682
- async getTask(params) {
1683
- const response = await this.request(`/a2a/${this.agentId}`, {
1684
- method: "POST",
1685
- body: {
1686
- method: "tasks/get",
1687
- params
1688
- }
2428
+ async cancelRun(runId) {
2429
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2430
+ return this.request(url, {
2431
+ method: "POST"
1689
2432
  });
1690
- return response;
1691
2433
  }
1692
2434
  /**
1693
- * Cancel a running task
1694
- * @param params - Parameters identifying the task to cancel
1695
- * @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`.
1696
2437
  */
1697
- async cancelTask(params) {
1698
- 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, {
1699
2441
  method: "POST",
1700
- body: {
1701
- method: "tasks/cancel",
1702
- params
1703
- }
2442
+ body: { event: params.event, data: params.data }
1704
2443
  });
1705
2444
  }
1706
2445
  };
1707
2446
 
1708
- // src/resources/mcp-tool.ts
1709
- var MCPTool = class extends BaseResource {
1710
- serverId;
1711
- toolId;
1712
- constructor(options, serverId, toolId) {
2447
+ // src/resources/observability.ts
2448
+ var Observability = class extends BaseResource {
2449
+ constructor(options) {
1713
2450
  super(options);
1714
- this.serverId = serverId;
1715
- this.toolId = toolId;
1716
2451
  }
1717
2452
  /**
1718
- * Retrieves details about this specific tool from the MCP server.
1719
- * @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
1720
2456
  */
1721
- details() {
1722
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2457
+ getTrace(traceId) {
2458
+ return this.request(`/api/observability/traces/${traceId}`);
1723
2459
  }
1724
2460
  /**
1725
- * Executes this specific tool on the MCP server.
1726
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1727
- * @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
1728
2464
  */
1729
- execute(params) {
1730
- const body = {};
1731
- if (params.data !== void 0) body.data = params.data;
1732
- if (params.runtimeContext !== void 0) {
1733
- body.runtimeContext = params.runtimeContext;
2465
+ getTraces(params) {
2466
+ const { pagination, filters } = params;
2467
+ const { page, perPage, dateRange } = pagination || {};
2468
+ const { name, spanType, entityId, entityType } = filters || {};
2469
+ const searchParams = new URLSearchParams();
2470
+ if (page !== void 0) {
2471
+ searchParams.set("page", String(page));
1734
2472
  }
1735
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1736
- method: "POST",
1737
- body: Object.keys(body).length > 0 ? body : void 0
1738
- });
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 (entityId && entityType) {
2483
+ searchParams.set("entityId", entityId);
2484
+ searchParams.set("entityType", entityType);
2485
+ }
2486
+ if (dateRange) {
2487
+ const dateRangeStr = JSON.stringify({
2488
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2489
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2490
+ });
2491
+ searchParams.set("dateRange", dateRangeStr);
2492
+ }
2493
+ const queryString = searchParams.toString();
2494
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
1739
2495
  }
1740
2496
  };
1741
2497
 
@@ -1803,7 +2559,7 @@ var NetworkMemoryThread = class extends BaseResource {
1803
2559
  };
1804
2560
 
1805
2561
  // src/resources/vNextNetwork.ts
1806
- var RECORD_SEPARATOR3 = "";
2562
+ var RECORD_SEPARATOR4 = "";
1807
2563
  var VNextNetwork = class extends BaseResource {
1808
2564
  constructor(options, networkId) {
1809
2565
  super(options);
@@ -1855,7 +2611,7 @@ var VNextNetwork = class extends BaseResource {
1855
2611
  if (done && !value) continue;
1856
2612
  try {
1857
2613
  const decoded = value ? new TextDecoder().decode(value) : "";
1858
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2614
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
1859
2615
  buffer = chunks.pop() || "";
1860
2616
  for (const chunk of chunks) {
1861
2617
  if (chunk) {
@@ -1942,8 +2698,10 @@ var VNextNetwork = class extends BaseResource {
1942
2698
 
1943
2699
  // src/client.ts
1944
2700
  var MastraClient = class extends BaseResource {
2701
+ observability;
1945
2702
  constructor(options) {
1946
2703
  super(options);
2704
+ this.observability = new Observability(options);
1947
2705
  }
1948
2706
  /**
1949
2707
  * Retrieves all available agents
@@ -1952,21 +2710,6 @@ var MastraClient = class extends BaseResource {
1952
2710
  getAgents() {
1953
2711
  return this.request("/api/agents");
1954
2712
  }
1955
- async getAGUI({ resourceId }) {
1956
- const agents = await this.getAgents();
1957
- return Object.entries(agents).reduce(
1958
- (acc, [agentId]) => {
1959
- const agent = this.getAgent(agentId);
1960
- acc[agentId] = new AGUIAdapter({
1961
- agentId,
1962
- agent,
1963
- resourceId
1964
- });
1965
- return acc;
1966
- },
1967
- {}
1968
- );
1969
- }
1970
2713
  /**
1971
2714
  * Gets an agent instance by ID
1972
2715
  * @param agentId - ID of the agent to retrieve
@@ -2072,7 +2815,7 @@ var MastraClient = class extends BaseResource {
2072
2815
  * @returns Tool instance
2073
2816
  */
2074
2817
  getTool(toolId) {
2075
- return new Tool2(this.options, toolId);
2818
+ return new Tool(this.options, toolId);
2076
2819
  }
2077
2820
  /**
2078
2821
  * Retrieves all available legacy workflows
@@ -2104,6 +2847,20 @@ var MastraClient = class extends BaseResource {
2104
2847
  getWorkflow(workflowId) {
2105
2848
  return new Workflow(this.options, workflowId);
2106
2849
  }
2850
+ /**
2851
+ * Gets all available agent builder actions
2852
+ * @returns Promise containing map of action IDs to action details
2853
+ */
2854
+ getAgentBuilderActions() {
2855
+ return this.request("/api/agent-builder/");
2856
+ }
2857
+ /**
2858
+ * Gets an agent builder instance for executing agent-builder workflows
2859
+ * @returns AgentBuilder instance
2860
+ */
2861
+ getAgentBuilderAction(actionId) {
2862
+ return new AgentBuilder(this.options, actionId);
2863
+ }
2107
2864
  /**
2108
2865
  * Gets a vector instance by name
2109
2866
  * @param vectorName - Name of the vector to retrieve
@@ -2454,6 +3211,12 @@ var MastraClient = class extends BaseResource {
2454
3211
  getModelProviders() {
2455
3212
  return this.request(`/api/model-providers`);
2456
3213
  }
3214
+ getAITrace(traceId) {
3215
+ return this.observability.getTrace(traceId);
3216
+ }
3217
+ getAITraces(params) {
3218
+ return this.observability.getTraces(params);
3219
+ }
2457
3220
  };
2458
3221
 
2459
3222
  exports.MastraClient = MastraClient;