@mastra/client-js 0.0.0-fix-message-list-args-missing-20250807205055 → 0.0.0-fix-bundle-cleanup-20250911062914

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 (76) hide show
  1. package/CHANGELOG.md +514 -3
  2. package/README.md +5 -3
  3. package/dist/client.d.ts +21 -6
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +1270 -369
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.js +1272 -371
  8. package/dist/index.js.map +1 -1
  9. package/dist/resources/a2a.d.ts +13 -16
  10. package/dist/resources/a2a.d.ts.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 +55 -7
  14. package/dist/resources/agent.d.ts.map +1 -1
  15. package/dist/resources/base.d.ts.map +1 -1
  16. package/dist/resources/index.d.ts +2 -0
  17. package/dist/resources/index.d.ts.map +1 -1
  18. package/dist/resources/memory-thread.d.ts +1 -1
  19. package/dist/resources/memory-thread.d.ts.map +1 -1
  20. package/dist/resources/network-memory-thread.d.ts +1 -1
  21. package/dist/resources/network-memory-thread.d.ts.map +1 -1
  22. package/dist/resources/network.d.ts +1 -1
  23. package/dist/resources/network.d.ts.map +1 -1
  24. package/dist/resources/observability.d.ts +19 -0
  25. package/dist/resources/observability.d.ts.map +1 -0
  26. package/dist/resources/tool.d.ts.map +1 -1
  27. package/dist/resources/vNextNetwork.d.ts +1 -1
  28. package/dist/resources/vNextNetwork.d.ts.map +1 -1
  29. package/dist/resources/workflow.d.ts +15 -0
  30. package/dist/resources/workflow.d.ts.map +1 -1
  31. package/dist/types.d.ts +49 -2
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/utils/process-client-tools.d.ts.map +1 -1
  34. package/dist/utils/process-mastra-stream.d.ts +11 -0
  35. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  36. package/dist/utils/zod-to-json-schema.d.ts +2 -104
  37. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  38. package/package.json +22 -16
  39. package/.turbo/turbo-build.log +0 -18
  40. package/dist/adapters/agui.d.ts +0 -23
  41. package/dist/adapters/agui.d.ts.map +0 -1
  42. package/eslint.config.js +0 -6
  43. package/integration-tests/agui-adapter.test.ts +0 -122
  44. package/integration-tests/package.json +0 -18
  45. package/integration-tests/src/mastra/index.ts +0 -35
  46. package/integration-tests/vitest.config.ts +0 -9
  47. package/src/adapters/agui.test.ts +0 -322
  48. package/src/adapters/agui.ts +0 -257
  49. package/src/client.ts +0 -623
  50. package/src/example.ts +0 -95
  51. package/src/index.test.ts +0 -1226
  52. package/src/index.ts +0 -3
  53. package/src/resources/a2a.ts +0 -88
  54. package/src/resources/agent.ts +0 -785
  55. package/src/resources/base.ts +0 -76
  56. package/src/resources/index.ts +0 -10
  57. package/src/resources/legacy-workflow.ts +0 -242
  58. package/src/resources/mcp-tool.ts +0 -48
  59. package/src/resources/memory-thread.test.ts +0 -285
  60. package/src/resources/memory-thread.ts +0 -99
  61. package/src/resources/network-memory-thread.test.ts +0 -269
  62. package/src/resources/network-memory-thread.ts +0 -81
  63. package/src/resources/network.ts +0 -86
  64. package/src/resources/tool.ts +0 -45
  65. package/src/resources/vNextNetwork.ts +0 -194
  66. package/src/resources/vector.ts +0 -83
  67. package/src/resources/workflow.ts +0 -410
  68. package/src/types.ts +0 -502
  69. package/src/utils/index.ts +0 -11
  70. package/src/utils/process-client-tools.ts +0 -32
  71. package/src/utils/zod-to-json-schema.ts +0 -10
  72. package/src/v2-messages.test.ts +0 -180
  73. package/tsconfig.build.json +0 -9
  74. package/tsconfig.json +0 -5
  75. package/tsup.config.ts +0 -17
  76. package/vitest.config.js +0 -8
package/dist/index.js CHANGED
@@ -1,217 +1,35 @@
1
- import { AbstractAgent, EventType } from '@ag-ui/client';
2
- import { Observable } from 'rxjs';
3
1
  import { processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
4
- import { ZodSchema } from 'zod';
5
- import originalZodToJsonSchema from 'zod-to-json-schema';
6
- import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
7
2
  import { v4 } from '@lukeed/uuid';
8
3
  import { RuntimeContext } from '@mastra/core/runtime-context';
4
+ import { isVercelTool } from '@mastra/core/tools/is-vercel-tool';
5
+ import { z } from 'zod';
6
+ import originalZodToJsonSchema from 'zod-to-json-schema';
9
7
 
10
- // src/adapters/agui.ts
11
- var AGUIAdapter = class extends AbstractAgent {
12
- agent;
13
- resourceId;
14
- constructor({ agent, agentId, resourceId, ...rest }) {
15
- super({
16
- agentId,
17
- ...rest
18
- });
19
- this.agent = agent;
20
- this.resourceId = resourceId;
21
- }
22
- run(input) {
23
- return new Observable((subscriber) => {
24
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
25
- subscriber.next({
26
- type: EventType.RUN_STARTED,
27
- threadId: input.threadId,
28
- runId: input.runId
29
- });
30
- this.agent.stream({
31
- threadId: input.threadId,
32
- resourceId: this.resourceId ?? "",
33
- runId: input.runId,
34
- messages: convertedMessages,
35
- clientTools: input.tools.reduce(
36
- (acc, tool) => {
37
- acc[tool.name] = {
38
- id: tool.name,
39
- description: tool.description,
40
- inputSchema: tool.parameters
41
- };
42
- return acc;
43
- },
44
- {}
45
- )
46
- }).then((response) => {
47
- let currentMessageId = void 0;
48
- let isInTextMessage = false;
49
- return response.processDataStream({
50
- onTextPart: (text) => {
51
- if (currentMessageId === void 0) {
52
- currentMessageId = generateUUID();
53
- const message2 = {
54
- type: EventType.TEXT_MESSAGE_START,
55
- messageId: currentMessageId,
56
- role: "assistant"
57
- };
58
- subscriber.next(message2);
59
- isInTextMessage = true;
60
- }
61
- const message = {
62
- type: EventType.TEXT_MESSAGE_CONTENT,
63
- messageId: currentMessageId,
64
- delta: text
65
- };
66
- subscriber.next(message);
67
- },
68
- onFinishMessagePart: () => {
69
- if (currentMessageId !== void 0) {
70
- const message = {
71
- type: EventType.TEXT_MESSAGE_END,
72
- messageId: currentMessageId
73
- };
74
- subscriber.next(message);
75
- isInTextMessage = false;
76
- }
77
- subscriber.next({
78
- type: EventType.RUN_FINISHED,
79
- threadId: input.threadId,
80
- runId: input.runId
81
- });
82
- subscriber.complete();
83
- },
84
- onToolCallPart(streamPart) {
85
- const parentMessageId = currentMessageId || generateUUID();
86
- if (isInTextMessage) {
87
- const message = {
88
- type: EventType.TEXT_MESSAGE_END,
89
- messageId: parentMessageId
90
- };
91
- subscriber.next(message);
92
- isInTextMessage = false;
93
- }
94
- subscriber.next({
95
- type: EventType.TOOL_CALL_START,
96
- toolCallId: streamPart.toolCallId,
97
- toolCallName: streamPart.toolName,
98
- parentMessageId
99
- });
100
- subscriber.next({
101
- type: EventType.TOOL_CALL_ARGS,
102
- toolCallId: streamPart.toolCallId,
103
- delta: JSON.stringify(streamPart.args),
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: EventType.TOOL_CALL_END,
108
- toolCallId: streamPart.toolCallId,
109
- parentMessageId
110
- });
111
- }
112
- });
113
- }).catch((error) => {
114
- console.error("error", error);
115
- subscriber.error(error);
116
- });
117
- return () => {
118
- };
119
- });
120
- }
121
- };
122
- function generateUUID() {
123
- if (typeof crypto !== "undefined") {
124
- if (typeof crypto.randomUUID === "function") {
125
- return crypto.randomUUID();
126
- }
127
- if (typeof crypto.getRandomValues === "function") {
128
- const buffer = new Uint8Array(16);
129
- crypto.getRandomValues(buffer);
130
- buffer[6] = buffer[6] & 15 | 64;
131
- buffer[8] = buffer[8] & 63 | 128;
132
- let hex = "";
133
- for (let i = 0; i < 16; i++) {
134
- hex += buffer[i].toString(16).padStart(2, "0");
135
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
136
- }
137
- return hex;
8
+ // src/resources/agent.ts
9
+ function parseClientRuntimeContext(runtimeContext) {
10
+ if (runtimeContext) {
11
+ if (runtimeContext instanceof RuntimeContext) {
12
+ return Object.fromEntries(runtimeContext.entries());
138
13
  }
14
+ return runtimeContext;
139
15
  }
140
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
141
- const r = Math.random() * 16 | 0;
142
- const v = c === "x" ? r : r & 3 | 8;
143
- return v.toString(16);
144
- });
16
+ return void 0;
145
17
  }
146
- function convertMessagesToMastraMessages(messages) {
147
- const result = [];
148
- const toolCallsWithResults = /* @__PURE__ */ new Set();
149
- for (const message of messages) {
150
- if (message.role === "tool" && message.toolCallId) {
151
- toolCallsWithResults.add(message.toolCallId);
152
- }
153
- }
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
- for (const toolCall of message.toolCalls) {
171
- if (!toolCallsWithResults.has(toolCall.id)) {
172
- result.push({
173
- role: "tool",
174
- content: [
175
- {
176
- type: "tool-result",
177
- toolCallId: toolCall.id,
178
- toolName: toolCall.function.name,
179
- result: JSON.parse(toolCall.function.arguments)
180
- // This is still wrong but matches test expectations
181
- }
182
- ]
183
- });
184
- }
185
- }
186
- }
187
- } else if (message.role === "user") {
188
- result.push({
189
- role: "user",
190
- content: message.content || ""
191
- });
192
- } else if (message.role === "tool") {
193
- result.push({
194
- role: "tool",
195
- content: [
196
- {
197
- type: "tool-result",
198
- toolCallId: message.toolCallId || "unknown",
199
- toolName: "unknown",
200
- // toolName is not available in tool messages from CopilotKit
201
- result: message.content
202
- }
203
- ]
204
- });
205
- }
206
- }
207
- return result;
18
+ function isZodType(value) {
19
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
208
20
  }
209
21
  function zodToJsonSchema(zodSchema) {
210
- if (!(zodSchema instanceof ZodSchema)) {
22
+ if (!isZodType(zodSchema)) {
211
23
  return zodSchema;
212
24
  }
213
- return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
25
+ if ("toJSONSchema" in z) {
26
+ const fn = "toJSONSchema";
27
+ return z[fn].call(z, zodSchema);
28
+ }
29
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "relative" });
214
30
  }
31
+
32
+ // src/utils/process-client-tools.ts
215
33
  function processClientTools(clientTools) {
216
34
  if (!clientTools) {
217
35
  return void 0;
@@ -240,6 +58,60 @@ function processClientTools(clientTools) {
240
58
  );
241
59
  }
242
60
 
61
+ // src/utils/process-mastra-stream.ts
62
+ async function sharedProcessMastraStream({
63
+ stream,
64
+ onChunk
65
+ }) {
66
+ const reader = stream.getReader();
67
+ const decoder = new TextDecoder();
68
+ let buffer = "";
69
+ try {
70
+ while (true) {
71
+ const { done, value } = await reader.read();
72
+ if (done) break;
73
+ buffer += decoder.decode(value, { stream: true });
74
+ const lines = buffer.split("\n\n");
75
+ buffer = lines.pop() || "";
76
+ for (const line of lines) {
77
+ if (line.startsWith("data: ")) {
78
+ const data = line.slice(6);
79
+ if (data === "[DONE]") {
80
+ console.log("\u{1F3C1} Stream finished");
81
+ return;
82
+ }
83
+ try {
84
+ const json = JSON.parse(data);
85
+ await onChunk(json);
86
+ } catch (error) {
87
+ console.error("\u274C JSON parse error:", error, "Data:", data);
88
+ }
89
+ }
90
+ }
91
+ }
92
+ } finally {
93
+ reader.releaseLock();
94
+ }
95
+ }
96
+ async function processMastraNetworkStream({
97
+ stream,
98
+ onChunk
99
+ }) {
100
+ return sharedProcessMastraStream({
101
+ stream,
102
+ onChunk
103
+ });
104
+ }
105
+ async function processMastraStream({
106
+ stream,
107
+ onChunk
108
+ }) {
109
+ return sharedProcessMastraStream({
110
+ stream,
111
+ onChunk
112
+ });
113
+ }
114
+
243
115
  // src/resources/base.ts
244
116
  var BaseResource = class {
245
117
  options;
@@ -254,7 +126,7 @@ var BaseResource = class {
254
126
  */
255
127
  async request(path, options = {}) {
256
128
  let lastError = null;
257
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
129
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
258
130
  let delay = backoffMs;
259
131
  for (let attempt = 0; attempt <= retries; attempt++) {
260
132
  try {
@@ -268,6 +140,7 @@ var BaseResource = class {
268
140
  // 'x-mastra-client-type': 'js',
269
141
  },
270
142
  signal: this.options.abortSignal,
143
+ credentials: options.credentials ?? credentials,
271
144
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
272
145
  });
273
146
  if (!response.ok) {
@@ -300,14 +173,64 @@ var BaseResource = class {
300
173
  throw lastError || new Error("Request failed");
301
174
  }
302
175
  };
303
- function parseClientRuntimeContext(runtimeContext) {
304
- if (runtimeContext) {
305
- if (runtimeContext instanceof RuntimeContext) {
306
- return Object.fromEntries(runtimeContext.entries());
176
+
177
+ // src/resources/agent.ts
178
+ async function executeToolCallAndRespond({
179
+ response,
180
+ params,
181
+ runId,
182
+ resourceId,
183
+ threadId,
184
+ runtimeContext,
185
+ respondFn
186
+ }) {
187
+ if (response.finishReason === "tool-calls") {
188
+ const toolCalls = response.toolCalls;
189
+ if (!toolCalls || !Array.isArray(toolCalls)) {
190
+ return response;
191
+ }
192
+ for (const toolCall of toolCalls) {
193
+ const clientTool = params.clientTools?.[toolCall.toolName];
194
+ if (clientTool && clientTool.execute) {
195
+ const result = await clientTool.execute(
196
+ {
197
+ context: toolCall?.args,
198
+ runId,
199
+ resourceId,
200
+ threadId,
201
+ runtimeContext,
202
+ tracingContext: { currentSpan: void 0 }
203
+ },
204
+ {
205
+ messages: response.messages,
206
+ toolCallId: toolCall?.toolCallId
207
+ }
208
+ );
209
+ const updatedMessages = [
210
+ {
211
+ role: "user",
212
+ content: params.messages
213
+ },
214
+ ...response.response.messages,
215
+ {
216
+ role: "tool",
217
+ content: [
218
+ {
219
+ type: "tool-result",
220
+ toolCallId: toolCall.toolCallId,
221
+ toolName: toolCall.toolName,
222
+ result
223
+ }
224
+ ]
225
+ }
226
+ ];
227
+ return respondFn({
228
+ ...params,
229
+ messages: updatedMessages
230
+ });
231
+ }
307
232
  }
308
- return runtimeContext;
309
233
  }
310
- return void 0;
311
234
  }
312
235
  var AgentVoice = class extends BaseResource {
313
236
  constructor(options, agentId) {
@@ -378,6 +301,12 @@ var Agent = class extends BaseResource {
378
301
  return this.request(`/api/agents/${this.agentId}`);
379
302
  }
380
303
  async generate(params) {
304
+ console.warn(
305
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 16th, 2025. Please use generateLegacy if you don't want to upgrade just yet."
306
+ );
307
+ return this.generateLegacy(params);
308
+ }
309
+ async generateLegacy(params) {
381
310
  const processedParams = {
382
311
  ...params,
383
312
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -387,7 +316,7 @@ var Agent = class extends BaseResource {
387
316
  };
388
317
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
389
318
  const response = await this.request(
390
- `/api/agents/${this.agentId}/generate`,
319
+ `/api/agents/${this.agentId}/generate-legacy`,
391
320
  {
392
321
  method: "POST",
393
322
  body: processedParams
@@ -402,7 +331,14 @@ var Agent = class extends BaseResource {
402
331
  const clientTool = params.clientTools?.[toolCall.toolName];
403
332
  if (clientTool && clientTool.execute) {
404
333
  const result = await clientTool.execute(
405
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
334
+ {
335
+ context: toolCall?.args,
336
+ runId,
337
+ resourceId,
338
+ threadId,
339
+ runtimeContext,
340
+ tracingContext: { currentSpan: void 0 }
341
+ },
406
342
  {
407
343
  messages: response.messages,
408
344
  toolCallId: toolCall?.toolCallId
@@ -435,6 +371,38 @@ var Agent = class extends BaseResource {
435
371
  }
436
372
  return response;
437
373
  }
374
+ async generateVNext(params) {
375
+ const processedParams = {
376
+ ...params,
377
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
378
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
379
+ clientTools: processClientTools(params.clientTools),
380
+ structuredOutput: params.structuredOutput ? {
381
+ ...params.structuredOutput,
382
+ schema: zodToJsonSchema(params.structuredOutput.schema)
383
+ } : void 0
384
+ };
385
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
386
+ const response = await this.request(
387
+ `/api/agents/${this.agentId}/generate/vnext`,
388
+ {
389
+ method: "POST",
390
+ body: processedParams
391
+ }
392
+ );
393
+ if (response.finishReason === "tool-calls") {
394
+ return executeToolCallAndRespond({
395
+ response,
396
+ params,
397
+ runId,
398
+ resourceId,
399
+ threadId,
400
+ runtimeContext,
401
+ respondFn: this.generateVNext.bind(this)
402
+ });
403
+ }
404
+ return response;
405
+ }
438
406
  async processChatResponse({
439
407
  stream,
440
408
  update,
@@ -703,6 +671,17 @@ var Agent = class extends BaseResource {
703
671
  * @returns Promise containing the enhanced Response object with processDataStream method
704
672
  */
705
673
  async stream(params) {
674
+ console.warn(
675
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 16th, 2025. Please use streamLegacy if you don't want to upgrade just yet."
676
+ );
677
+ return this.streamLegacy(params);
678
+ }
679
+ /**
680
+ * Streams a response from the agent
681
+ * @param params - Stream parameters including prompt
682
+ * @returns Promise containing the enhanced Response object with processDataStream method
683
+ */
684
+ async streamLegacy(params) {
706
685
  const processedParams = {
707
686
  ...params,
708
687
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -725,11 +704,261 @@ var Agent = class extends BaseResource {
725
704
  };
726
705
  return streamResponse;
727
706
  }
728
- /**
729
- * Processes the stream response and handles tool calls
730
- */
731
- async processStreamResponse(processedParams, writable) {
732
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
707
+ async processChatResponse_vNext({
708
+ stream,
709
+ update,
710
+ onToolCall,
711
+ onFinish,
712
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
713
+ lastMessage
714
+ }) {
715
+ const replaceLastMessage = lastMessage?.role === "assistant";
716
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
717
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
718
+ return Math.max(max, toolInvocation.step ?? 0);
719
+ }, 0) ?? 0) : 0;
720
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
721
+ id: v4(),
722
+ createdAt: getCurrentDate(),
723
+ role: "assistant",
724
+ content: "",
725
+ parts: []
726
+ };
727
+ let currentTextPart = void 0;
728
+ let currentReasoningPart = void 0;
729
+ let currentReasoningTextDetail = void 0;
730
+ function updateToolInvocationPart(toolCallId, invocation) {
731
+ const part = message.parts.find(
732
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
733
+ );
734
+ if (part != null) {
735
+ part.toolInvocation = invocation;
736
+ } else {
737
+ message.parts.push({
738
+ type: "tool-invocation",
739
+ toolInvocation: invocation
740
+ });
741
+ }
742
+ }
743
+ const data = [];
744
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
745
+ const partialToolCalls = {};
746
+ let usage = {
747
+ completionTokens: NaN,
748
+ promptTokens: NaN,
749
+ totalTokens: NaN
750
+ };
751
+ let finishReason = "unknown";
752
+ function execUpdate() {
753
+ const copiedData = [...data];
754
+ if (messageAnnotations?.length) {
755
+ message.annotations = messageAnnotations;
756
+ }
757
+ const copiedMessage = {
758
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
759
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
760
+ ...structuredClone(message),
761
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
762
+ // hashing approach by default to detect changes, but it only works for shallow
763
+ // changes. This is why we need to add a revision id to ensure that the message
764
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
765
+ // forwarded to rendering):
766
+ revisionId: v4()
767
+ };
768
+ update({
769
+ message: copiedMessage,
770
+ data: copiedData,
771
+ replaceLastMessage
772
+ });
773
+ }
774
+ await processMastraStream({
775
+ stream,
776
+ // TODO: casting as any here because the stream types were all typed as any before in core.
777
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
778
+ onChunk: async (chunk) => {
779
+ switch (chunk.type) {
780
+ case "step-start": {
781
+ if (!replaceLastMessage) {
782
+ message.id = chunk.payload.messageId;
783
+ }
784
+ message.parts.push({ type: "step-start" });
785
+ execUpdate();
786
+ break;
787
+ }
788
+ case "text-delta": {
789
+ if (currentTextPart == null) {
790
+ currentTextPart = {
791
+ type: "text",
792
+ text: chunk.payload.text
793
+ };
794
+ message.parts.push(currentTextPart);
795
+ } else {
796
+ currentTextPart.text += chunk.payload.text;
797
+ }
798
+ message.content += chunk.payload.text;
799
+ execUpdate();
800
+ break;
801
+ }
802
+ case "reasoning-delta": {
803
+ if (currentReasoningTextDetail == null) {
804
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
805
+ if (currentReasoningPart != null) {
806
+ currentReasoningPart.details.push(currentReasoningTextDetail);
807
+ }
808
+ } else {
809
+ currentReasoningTextDetail.text += chunk.payload.text;
810
+ }
811
+ if (currentReasoningPart == null) {
812
+ currentReasoningPart = {
813
+ type: "reasoning",
814
+ reasoning: chunk.payload.text,
815
+ details: [currentReasoningTextDetail]
816
+ };
817
+ message.parts.push(currentReasoningPart);
818
+ } else {
819
+ currentReasoningPart.reasoning += chunk.payload.text;
820
+ }
821
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
822
+ execUpdate();
823
+ break;
824
+ }
825
+ case "file": {
826
+ message.parts.push({
827
+ type: "file",
828
+ mimeType: chunk.payload.mimeType,
829
+ data: chunk.payload.data
830
+ });
831
+ execUpdate();
832
+ break;
833
+ }
834
+ case "source": {
835
+ message.parts.push({
836
+ type: "source",
837
+ source: chunk.payload.source
838
+ });
839
+ execUpdate();
840
+ break;
841
+ }
842
+ case "tool-call": {
843
+ const invocation = {
844
+ state: "call",
845
+ step,
846
+ ...chunk.payload
847
+ };
848
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
849
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
850
+ } else {
851
+ if (message.toolInvocations == null) {
852
+ message.toolInvocations = [];
853
+ }
854
+ message.toolInvocations.push(invocation);
855
+ }
856
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
857
+ execUpdate();
858
+ if (onToolCall) {
859
+ const result = await onToolCall({ toolCall: chunk.payload });
860
+ if (result != null) {
861
+ const invocation2 = {
862
+ state: "result",
863
+ step,
864
+ ...chunk.payload,
865
+ result
866
+ };
867
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
868
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
869
+ execUpdate();
870
+ }
871
+ }
872
+ }
873
+ case "tool-call-input-streaming-start": {
874
+ if (message.toolInvocations == null) {
875
+ message.toolInvocations = [];
876
+ }
877
+ partialToolCalls[chunk.payload.toolCallId] = {
878
+ text: "",
879
+ step,
880
+ toolName: chunk.payload.toolName,
881
+ index: message.toolInvocations.length
882
+ };
883
+ const invocation = {
884
+ state: "partial-call",
885
+ step,
886
+ toolCallId: chunk.payload.toolCallId,
887
+ toolName: chunk.payload.toolName,
888
+ args: chunk.payload.args
889
+ };
890
+ message.toolInvocations.push(invocation);
891
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
892
+ execUpdate();
893
+ break;
894
+ }
895
+ case "tool-call-delta": {
896
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
897
+ partialToolCall.text += chunk.payload.argsTextDelta;
898
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
899
+ const invocation = {
900
+ state: "partial-call",
901
+ step: partialToolCall.step,
902
+ toolCallId: chunk.payload.toolCallId,
903
+ toolName: partialToolCall.toolName,
904
+ args: partialArgs
905
+ };
906
+ message.toolInvocations[partialToolCall.index] = invocation;
907
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
908
+ execUpdate();
909
+ break;
910
+ }
911
+ case "tool-result": {
912
+ const toolInvocations = message.toolInvocations;
913
+ if (toolInvocations == null) {
914
+ throw new Error("tool_result must be preceded by a tool_call");
915
+ }
916
+ const toolInvocationIndex = toolInvocations.findIndex(
917
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
918
+ );
919
+ if (toolInvocationIndex === -1) {
920
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
921
+ }
922
+ const invocation = {
923
+ ...toolInvocations[toolInvocationIndex],
924
+ state: "result",
925
+ ...chunk.payload
926
+ };
927
+ toolInvocations[toolInvocationIndex] = invocation;
928
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "error": {
933
+ throw new Error(chunk.payload.error);
934
+ }
935
+ case "data": {
936
+ data.push(...chunk.payload.data);
937
+ execUpdate();
938
+ break;
939
+ }
940
+ case "step-finish": {
941
+ step += 1;
942
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
943
+ currentReasoningPart = void 0;
944
+ currentReasoningTextDetail = void 0;
945
+ execUpdate();
946
+ break;
947
+ }
948
+ case "finish": {
949
+ finishReason = chunk.payload.stepResult.reason;
950
+ if (chunk.payload.usage != null) {
951
+ usage = chunk.payload.usage;
952
+ }
953
+ break;
954
+ }
955
+ }
956
+ }
957
+ });
958
+ onFinish?.({ message, finishReason, usage });
959
+ }
960
+ async processStreamResponse_vNext(processedParams, writable) {
961
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
733
962
  method: "POST",
734
963
  body: processedParams,
735
964
  stream: true
@@ -741,12 +970,31 @@ var Agent = class extends BaseResource {
741
970
  let toolCalls = [];
742
971
  let messages = [];
743
972
  const [streamForWritable, streamForProcessing] = response.body.tee();
744
- streamForWritable.pipeTo(writable, {
745
- preventClose: true
746
- }).catch((error) => {
973
+ streamForWritable.pipeTo(
974
+ new WritableStream({
975
+ async write(chunk) {
976
+ try {
977
+ const text = new TextDecoder().decode(chunk);
978
+ if (text.includes("[DONE]")) {
979
+ return;
980
+ }
981
+ } catch {
982
+ }
983
+ const writer = writable.getWriter();
984
+ try {
985
+ await writer.write(chunk);
986
+ } finally {
987
+ writer.releaseLock();
988
+ }
989
+ }
990
+ }),
991
+ {
992
+ preventClose: true
993
+ }
994
+ ).catch((error) => {
747
995
  console.error("Error piping to writable stream:", error);
748
996
  });
749
- this.processChatResponse({
997
+ this.processChatResponse_vNext({
750
998
  stream: streamForProcessing,
751
999
  update: ({ message }) => {
752
1000
  const existingIndex = messages.findIndex((m) => m.id === message.id);
@@ -771,14 +1019,171 @@ var Agent = class extends BaseResource {
771
1019
  runId: processedParams.runId,
772
1020
  resourceId: processedParams.resourceId,
773
1021
  threadId: processedParams.threadId,
774
- runtimeContext: processedParams.runtimeContext
1022
+ runtimeContext: processedParams.runtimeContext,
1023
+ // TODO: Pass proper tracing context when client-js supports tracing
1024
+ tracingContext: { currentSpan: void 0 }
775
1025
  },
776
1026
  {
777
1027
  messages: response.messages,
778
1028
  toolCallId: toolCall2?.toolCallId
779
1029
  }
780
1030
  );
781
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1031
+ const lastMessageRaw = messages[messages.length - 1];
1032
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1033
+ const toolInvocationPart = lastMessage?.parts?.find(
1034
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1035
+ );
1036
+ if (toolInvocationPart) {
1037
+ toolInvocationPart.toolInvocation = {
1038
+ ...toolInvocationPart.toolInvocation,
1039
+ state: "result",
1040
+ result
1041
+ };
1042
+ }
1043
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1044
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1045
+ );
1046
+ if (toolInvocation) {
1047
+ toolInvocation.state = "result";
1048
+ toolInvocation.result = result;
1049
+ }
1050
+ const originalMessages = processedParams.messages;
1051
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1052
+ const updatedMessages = lastMessage != null ? [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messageArray, ...messages];
1053
+ this.processStreamResponse_vNext(
1054
+ {
1055
+ ...processedParams,
1056
+ messages: updatedMessages
1057
+ },
1058
+ writable
1059
+ ).catch((error) => {
1060
+ console.error("Error processing stream response:", error);
1061
+ });
1062
+ }
1063
+ }
1064
+ } else {
1065
+ setTimeout(() => {
1066
+ writable.close();
1067
+ }, 0);
1068
+ }
1069
+ },
1070
+ lastMessage: void 0
1071
+ }).catch((error) => {
1072
+ console.error("Error processing stream response:", error);
1073
+ });
1074
+ } catch (error) {
1075
+ console.error("Error processing stream response:", error);
1076
+ }
1077
+ return response;
1078
+ }
1079
+ async network(params) {
1080
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1081
+ method: "POST",
1082
+ body: params,
1083
+ stream: true
1084
+ });
1085
+ if (!response.body) {
1086
+ throw new Error("No response body");
1087
+ }
1088
+ const streamResponse = new Response(response.body, {
1089
+ status: response.status,
1090
+ statusText: response.statusText,
1091
+ headers: response.headers
1092
+ });
1093
+ streamResponse.processDataStream = async ({
1094
+ onChunk
1095
+ }) => {
1096
+ await processMastraNetworkStream({
1097
+ stream: streamResponse.body,
1098
+ onChunk
1099
+ });
1100
+ };
1101
+ return streamResponse;
1102
+ }
1103
+ async streamVNext(params) {
1104
+ const processedParams = {
1105
+ ...params,
1106
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1107
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1108
+ clientTools: processClientTools(params.clientTools),
1109
+ structuredOutput: params.structuredOutput ? {
1110
+ ...params.structuredOutput,
1111
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1112
+ } : void 0
1113
+ };
1114
+ const { readable, writable } = new TransformStream();
1115
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1116
+ const streamResponse = new Response(readable, {
1117
+ status: response.status,
1118
+ statusText: response.statusText,
1119
+ headers: response.headers
1120
+ });
1121
+ streamResponse.processDataStream = async ({
1122
+ onChunk
1123
+ }) => {
1124
+ await processMastraStream({
1125
+ stream: streamResponse.body,
1126
+ onChunk
1127
+ });
1128
+ };
1129
+ return streamResponse;
1130
+ }
1131
+ /**
1132
+ * Processes the stream response and handles tool calls
1133
+ */
1134
+ async processStreamResponse(processedParams, writable) {
1135
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1136
+ method: "POST",
1137
+ body: processedParams,
1138
+ stream: true
1139
+ });
1140
+ if (!response.body) {
1141
+ throw new Error("No response body");
1142
+ }
1143
+ try {
1144
+ let toolCalls = [];
1145
+ let messages = [];
1146
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1147
+ streamForWritable.pipeTo(writable, {
1148
+ preventClose: true
1149
+ }).catch((error) => {
1150
+ console.error("Error piping to writable stream:", error);
1151
+ });
1152
+ this.processChatResponse({
1153
+ stream: streamForProcessing,
1154
+ update: ({ message }) => {
1155
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1156
+ if (existingIndex !== -1) {
1157
+ messages[existingIndex] = message;
1158
+ } else {
1159
+ messages.push(message);
1160
+ }
1161
+ },
1162
+ onFinish: async ({ finishReason, message }) => {
1163
+ if (finishReason === "tool-calls") {
1164
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1165
+ if (toolCall) {
1166
+ toolCalls.push(toolCall);
1167
+ }
1168
+ for (const toolCall2 of toolCalls) {
1169
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1170
+ if (clientTool && clientTool.execute) {
1171
+ const result = await clientTool.execute(
1172
+ {
1173
+ context: toolCall2?.args,
1174
+ runId: processedParams.runId,
1175
+ resourceId: processedParams.resourceId,
1176
+ threadId: processedParams.threadId,
1177
+ runtimeContext: processedParams.runtimeContext,
1178
+ // TODO: Pass proper tracing context when client-js supports tracing
1179
+ tracingContext: { currentSpan: void 0 }
1180
+ },
1181
+ {
1182
+ messages: response.messages,
1183
+ toolCallId: toolCall2?.toolCallId
1184
+ }
1185
+ );
1186
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
782
1187
  const toolInvocationPart = lastMessage?.parts?.find(
783
1188
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
784
1189
  );
@@ -875,6 +1280,17 @@ var Agent = class extends BaseResource {
875
1280
  liveEvals() {
876
1281
  return this.request(`/api/agents/${this.agentId}/evals/live`);
877
1282
  }
1283
+ /**
1284
+ * Updates the model for the agent
1285
+ * @param params - Parameters for updating the model
1286
+ * @returns Promise containing the updated model
1287
+ */
1288
+ updateModel(params) {
1289
+ return this.request(`/api/agents/${this.agentId}/model`, {
1290
+ method: "POST",
1291
+ body: params
1292
+ });
1293
+ }
878
1294
  };
879
1295
  var Network = class extends BaseResource {
880
1296
  constructor(options, networkId) {
@@ -1259,7 +1675,7 @@ var LegacyWorkflow = class extends BaseResource {
1259
1675
  };
1260
1676
 
1261
1677
  // src/resources/tool.ts
1262
- var Tool2 = class extends BaseResource {
1678
+ var Tool = class extends BaseResource {
1263
1679
  constructor(options, toolId) {
1264
1680
  super(options);
1265
1681
  this.toolId = toolId;
@@ -1483,32 +1899,472 @@ var Workflow = class extends BaseResource {
1483
1899
  searchParams.set("runId", params.runId);
1484
1900
  }
1485
1901
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1486
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1902
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1903
+ method: "POST",
1904
+ body: { inputData: params.inputData, runtimeContext }
1905
+ });
1906
+ }
1907
+ /**
1908
+ * Starts a workflow run and returns a stream
1909
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1910
+ * @returns Promise containing the workflow execution results
1911
+ */
1912
+ async stream(params) {
1913
+ const searchParams = new URLSearchParams();
1914
+ if (!!params?.runId) {
1915
+ searchParams.set("runId", params.runId);
1916
+ }
1917
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1918
+ const response = await this.request(
1919
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1920
+ {
1921
+ method: "POST",
1922
+ body: { inputData: params.inputData, runtimeContext },
1923
+ stream: true
1924
+ }
1925
+ );
1926
+ if (!response.ok) {
1927
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1928
+ }
1929
+ if (!response.body) {
1930
+ throw new Error("Response body is null");
1931
+ }
1932
+ let failedChunk = void 0;
1933
+ const transformStream = new TransformStream({
1934
+ start() {
1935
+ },
1936
+ async transform(chunk, controller) {
1937
+ try {
1938
+ const decoded = new TextDecoder().decode(chunk);
1939
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1940
+ for (const chunk2 of chunks) {
1941
+ if (chunk2) {
1942
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1943
+ try {
1944
+ const parsedChunk = JSON.parse(newChunk);
1945
+ controller.enqueue(parsedChunk);
1946
+ failedChunk = void 0;
1947
+ } catch {
1948
+ failedChunk = newChunk;
1949
+ }
1950
+ }
1951
+ }
1952
+ } catch {
1953
+ }
1954
+ }
1955
+ });
1956
+ return response.body.pipeThrough(transformStream);
1957
+ }
1958
+ /**
1959
+ * Starts a workflow run and returns a stream
1960
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1961
+ * @returns Promise containing the workflow execution results
1962
+ */
1963
+ async streamVNext(params) {
1964
+ const searchParams = new URLSearchParams();
1965
+ if (!!params?.runId) {
1966
+ searchParams.set("runId", params.runId);
1967
+ }
1968
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1969
+ const response = await this.request(
1970
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1971
+ {
1972
+ method: "POST",
1973
+ body: { inputData: params.inputData, runtimeContext },
1974
+ stream: true
1975
+ }
1976
+ );
1977
+ if (!response.ok) {
1978
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1979
+ }
1980
+ if (!response.body) {
1981
+ throw new Error("Response body is null");
1982
+ }
1983
+ let failedChunk = void 0;
1984
+ const transformStream = new TransformStream({
1985
+ start() {
1986
+ },
1987
+ async transform(chunk, controller) {
1988
+ try {
1989
+ const decoded = new TextDecoder().decode(chunk);
1990
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1991
+ for (const chunk2 of chunks) {
1992
+ if (chunk2) {
1993
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1994
+ try {
1995
+ const parsedChunk = JSON.parse(newChunk);
1996
+ controller.enqueue(parsedChunk);
1997
+ failedChunk = void 0;
1998
+ } catch {
1999
+ failedChunk = newChunk;
2000
+ }
2001
+ }
2002
+ }
2003
+ } catch {
2004
+ }
2005
+ }
2006
+ });
2007
+ return response.body.pipeThrough(transformStream);
2008
+ }
2009
+ /**
2010
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2011
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2012
+ * @returns Promise containing the workflow resume results
2013
+ */
2014
+ resumeAsync(params) {
2015
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2016
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2017
+ method: "POST",
2018
+ body: {
2019
+ step: params.step,
2020
+ resumeData: params.resumeData,
2021
+ runtimeContext
2022
+ }
2023
+ });
2024
+ }
2025
+ /**
2026
+ * Watches workflow transitions in real-time
2027
+ * @param runId - Optional run ID to filter the watch stream
2028
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2029
+ */
2030
+ async watch({ runId }, onRecord) {
2031
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2032
+ stream: true
2033
+ });
2034
+ if (!response.ok) {
2035
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2036
+ }
2037
+ if (!response.body) {
2038
+ throw new Error("Response body is null");
2039
+ }
2040
+ for await (const record of this.streamProcessor(response.body)) {
2041
+ if (typeof record === "string") {
2042
+ onRecord(JSON.parse(record));
2043
+ } else {
2044
+ onRecord(record);
2045
+ }
2046
+ }
2047
+ }
2048
+ /**
2049
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2050
+ * serializing each as JSON and separating them with the record separator (\x1E).
2051
+ *
2052
+ * @param records - An iterable or async iterable of objects to stream
2053
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2054
+ */
2055
+ static createRecordStream(records) {
2056
+ const encoder = new TextEncoder();
2057
+ return new ReadableStream({
2058
+ async start(controller) {
2059
+ try {
2060
+ for await (const record of records) {
2061
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2062
+ controller.enqueue(encoder.encode(json));
2063
+ }
2064
+ controller.close();
2065
+ } catch (err) {
2066
+ controller.error(err);
2067
+ }
2068
+ }
2069
+ });
2070
+ }
2071
+ };
2072
+
2073
+ // src/resources/a2a.ts
2074
+ var A2A = class extends BaseResource {
2075
+ constructor(options, agentId) {
2076
+ super(options);
2077
+ this.agentId = agentId;
2078
+ }
2079
+ /**
2080
+ * Get the agent card with metadata about the agent
2081
+ * @returns Promise containing the agent card information
2082
+ */
2083
+ async getCard() {
2084
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2085
+ }
2086
+ /**
2087
+ * Send a message to the agent and gets a message or task response
2088
+ * @param params - Parameters for the task
2089
+ * @returns Promise containing the response
2090
+ */
2091
+ async sendMessage(params) {
2092
+ const response = await this.request(`/a2a/${this.agentId}`, {
2093
+ method: "POST",
2094
+ body: {
2095
+ method: "message/send",
2096
+ params
2097
+ }
2098
+ });
2099
+ return response;
2100
+ }
2101
+ /**
2102
+ * Sends a message to an agent to initiate/continue a task and subscribes
2103
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2104
+ * @param params - Parameters for the task
2105
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2106
+ */
2107
+ async sendStreamingMessage(params) {
2108
+ const response = await this.request(`/a2a/${this.agentId}`, {
2109
+ method: "POST",
2110
+ body: {
2111
+ method: "message/stream",
2112
+ params
2113
+ }
2114
+ });
2115
+ return response;
2116
+ }
2117
+ /**
2118
+ * Get the status and result of a task
2119
+ * @param params - Parameters for querying the task
2120
+ * @returns Promise containing the task response
2121
+ */
2122
+ async getTask(params) {
2123
+ const response = await this.request(`/a2a/${this.agentId}`, {
2124
+ method: "POST",
2125
+ body: {
2126
+ method: "tasks/get",
2127
+ params
2128
+ }
2129
+ });
2130
+ return response;
2131
+ }
2132
+ /**
2133
+ * Cancel a running task
2134
+ * @param params - Parameters identifying the task to cancel
2135
+ * @returns Promise containing the task response
2136
+ */
2137
+ async cancelTask(params) {
2138
+ return this.request(`/a2a/${this.agentId}`, {
2139
+ method: "POST",
2140
+ body: {
2141
+ method: "tasks/cancel",
2142
+ params
2143
+ }
2144
+ });
2145
+ }
2146
+ };
2147
+
2148
+ // src/resources/mcp-tool.ts
2149
+ var MCPTool = class extends BaseResource {
2150
+ serverId;
2151
+ toolId;
2152
+ constructor(options, serverId, toolId) {
2153
+ super(options);
2154
+ this.serverId = serverId;
2155
+ this.toolId = toolId;
2156
+ }
2157
+ /**
2158
+ * Retrieves details about this specific tool from the MCP server.
2159
+ * @returns Promise containing the tool's information (name, description, schema).
2160
+ */
2161
+ details() {
2162
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2163
+ }
2164
+ /**
2165
+ * Executes this specific tool on the MCP server.
2166
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2167
+ * @returns Promise containing the result of the tool execution.
2168
+ */
2169
+ execute(params) {
2170
+ const body = {};
2171
+ if (params.data !== void 0) body.data = params.data;
2172
+ if (params.runtimeContext !== void 0) {
2173
+ body.runtimeContext = params.runtimeContext;
2174
+ }
2175
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2176
+ method: "POST",
2177
+ body: Object.keys(body).length > 0 ? body : void 0
2178
+ });
2179
+ }
2180
+ };
2181
+
2182
+ // src/resources/agent-builder.ts
2183
+ var RECORD_SEPARATOR3 = "";
2184
+ var AgentBuilder = class extends BaseResource {
2185
+ constructor(options, actionId) {
2186
+ super(options);
2187
+ this.actionId = actionId;
2188
+ }
2189
+ // Helper function to transform workflow result to action result
2190
+ transformWorkflowResult(result) {
2191
+ if (result.status === "success") {
2192
+ return {
2193
+ success: result.result.success || false,
2194
+ applied: result.result.applied || false,
2195
+ branchName: result.result.branchName,
2196
+ message: result.result.message || "Agent builder action completed",
2197
+ validationResults: result.result.validationResults,
2198
+ error: result.result.error,
2199
+ errors: result.result.errors,
2200
+ stepResults: result.result.stepResults
2201
+ };
2202
+ } else if (result.status === "failed") {
2203
+ return {
2204
+ success: false,
2205
+ applied: false,
2206
+ message: `Agent builder action failed: ${result.error.message}`,
2207
+ error: result.error.message
2208
+ };
2209
+ } else {
2210
+ return {
2211
+ success: false,
2212
+ applied: false,
2213
+ message: "Agent builder action was suspended",
2214
+ error: "Workflow suspended - manual intervention required"
2215
+ };
2216
+ }
2217
+ }
2218
+ /**
2219
+ * Creates a new agent builder action run and returns the runId.
2220
+ * This calls `/api/agent-builder/:actionId/create-run`.
2221
+ */
2222
+ async createRun(params) {
2223
+ const searchParams = new URLSearchParams();
2224
+ if (!!params?.runId) {
2225
+ searchParams.set("runId", params.runId);
2226
+ }
2227
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2228
+ return this.request(url, {
2229
+ method: "POST"
2230
+ });
2231
+ }
2232
+ /**
2233
+ * Creates a new workflow run (alias for createRun)
2234
+ * @param params - Optional object containing the optional runId
2235
+ * @returns Promise containing the runId of the created run
2236
+ */
2237
+ createRunAsync(params) {
2238
+ return this.createRun(params);
2239
+ }
2240
+ /**
2241
+ * Starts agent builder action asynchronously and waits for completion.
2242
+ * This calls `/api/agent-builder/:actionId/start-async`.
2243
+ */
2244
+ async startAsync(params, runId) {
2245
+ const searchParams = new URLSearchParams();
2246
+ if (runId) {
2247
+ searchParams.set("runId", runId);
2248
+ }
2249
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2250
+ const { runtimeContext: _, ...actionParams } = params;
2251
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2252
+ const result = await this.request(url, {
2253
+ method: "POST",
2254
+ body: { ...actionParams, runtimeContext }
2255
+ });
2256
+ return this.transformWorkflowResult(result);
2257
+ }
2258
+ /**
2259
+ * Starts an existing agent builder action run.
2260
+ * This calls `/api/agent-builder/:actionId/start`.
2261
+ */
2262
+ async startActionRun(params, runId) {
2263
+ const searchParams = new URLSearchParams();
2264
+ searchParams.set("runId", runId);
2265
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2266
+ const { runtimeContext: _, ...actionParams } = params;
2267
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2268
+ return this.request(url, {
2269
+ method: "POST",
2270
+ body: { ...actionParams, runtimeContext }
2271
+ });
2272
+ }
2273
+ /**
2274
+ * Resumes a suspended agent builder action step.
2275
+ * This calls `/api/agent-builder/:actionId/resume`.
2276
+ */
2277
+ async resume(params, runId) {
2278
+ const searchParams = new URLSearchParams();
2279
+ searchParams.set("runId", runId);
2280
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2281
+ const { runtimeContext: _, ...resumeParams } = params;
2282
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2283
+ return this.request(url, {
2284
+ method: "POST",
2285
+ body: { ...resumeParams, runtimeContext }
2286
+ });
2287
+ }
2288
+ /**
2289
+ * Resumes a suspended agent builder action step asynchronously.
2290
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2291
+ */
2292
+ async resumeAsync(params, runId) {
2293
+ const searchParams = new URLSearchParams();
2294
+ searchParams.set("runId", runId);
2295
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2296
+ const { runtimeContext: _, ...resumeParams } = params;
2297
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2298
+ const result = await this.request(url, {
1487
2299
  method: "POST",
1488
- body: { inputData: params.inputData, runtimeContext }
2300
+ body: { ...resumeParams, runtimeContext }
1489
2301
  });
2302
+ return this.transformWorkflowResult(result);
1490
2303
  }
1491
2304
  /**
1492
- * Starts a workflow run and returns a stream
1493
- * @param params - Object containing the optional runId, inputData and runtimeContext
1494
- * @returns Promise containing the workflow execution results
2305
+ * Creates an async generator that processes a readable stream and yields action records
2306
+ * separated by the Record Separator character (\x1E)
2307
+ *
2308
+ * @param stream - The readable stream to process
2309
+ * @returns An async generator that yields parsed records
1495
2310
  */
1496
- async stream(params) {
2311
+ async *streamProcessor(stream) {
2312
+ const reader = stream.getReader();
2313
+ let doneReading = false;
2314
+ let buffer = "";
2315
+ try {
2316
+ while (!doneReading) {
2317
+ const { done, value } = await reader.read();
2318
+ doneReading = done;
2319
+ if (done && !value) continue;
2320
+ try {
2321
+ const decoded = value ? new TextDecoder().decode(value) : "";
2322
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2323
+ buffer = chunks.pop() || "";
2324
+ for (const chunk of chunks) {
2325
+ if (chunk) {
2326
+ if (typeof chunk === "string") {
2327
+ try {
2328
+ const parsedChunk = JSON.parse(chunk);
2329
+ yield parsedChunk;
2330
+ } catch {
2331
+ }
2332
+ }
2333
+ }
2334
+ }
2335
+ } catch {
2336
+ }
2337
+ }
2338
+ if (buffer) {
2339
+ try {
2340
+ yield JSON.parse(buffer);
2341
+ } catch {
2342
+ }
2343
+ }
2344
+ } finally {
2345
+ reader.cancel().catch(() => {
2346
+ });
2347
+ }
2348
+ }
2349
+ /**
2350
+ * Streams agent builder action progress in real-time.
2351
+ * This calls `/api/agent-builder/:actionId/stream`.
2352
+ */
2353
+ async stream(params, runId) {
1497
2354
  const searchParams = new URLSearchParams();
1498
- if (!!params?.runId) {
1499
- searchParams.set("runId", params.runId);
2355
+ if (runId) {
2356
+ searchParams.set("runId", runId);
1500
2357
  }
1501
2358
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1502
- const response = await this.request(
1503
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1504
- {
1505
- method: "POST",
1506
- body: { inputData: params.inputData, runtimeContext },
1507
- stream: true
1508
- }
1509
- );
2359
+ const { runtimeContext: _, ...actionParams } = params;
2360
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2361
+ const response = await this.request(url, {
2362
+ method: "POST",
2363
+ body: { ...actionParams, runtimeContext },
2364
+ stream: true
2365
+ });
1510
2366
  if (!response.ok) {
1511
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2367
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1512
2368
  }
1513
2369
  if (!response.body) {
1514
2370
  throw new Error("Response body is null");
@@ -1520,7 +2376,7 @@ var Workflow = class extends BaseResource {
1520
2376
  async transform(chunk, controller) {
1521
2377
  try {
1522
2378
  const decoded = new TextDecoder().decode(chunk);
1523
- const chunks = decoded.split(RECORD_SEPARATOR2);
2379
+ const chunks = decoded.split(RECORD_SEPARATOR3);
1524
2380
  for (const chunk2 of chunks) {
1525
2381
  if (chunk2) {
1526
2382
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1528,7 +2384,7 @@ var Workflow = class extends BaseResource {
1528
2384
  const parsedChunk = JSON.parse(newChunk);
1529
2385
  controller.enqueue(parsedChunk);
1530
2386
  failedChunk = void 0;
1531
- } catch (error) {
2387
+ } catch {
1532
2388
  failedChunk = newChunk;
1533
2389
  }
1534
2390
  }
@@ -1540,32 +2396,68 @@ var Workflow = class extends BaseResource {
1540
2396
  return response.body.pipeThrough(transformStream);
1541
2397
  }
1542
2398
  /**
1543
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1544
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1545
- * @returns Promise containing the workflow resume results
2399
+ * Streams agent builder action progress in real-time using VNext streaming.
2400
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1546
2401
  */
1547
- resumeAsync(params) {
2402
+ async streamVNext(params, runId) {
2403
+ const searchParams = new URLSearchParams();
2404
+ if (runId) {
2405
+ searchParams.set("runId", runId);
2406
+ }
1548
2407
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1549
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2408
+ const { runtimeContext: _, ...actionParams } = params;
2409
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2410
+ const response = await this.request(url, {
1550
2411
  method: "POST",
1551
- body: {
1552
- step: params.step,
1553
- resumeData: params.resumeData,
1554
- runtimeContext
2412
+ body: { ...actionParams, runtimeContext },
2413
+ stream: true
2414
+ });
2415
+ if (!response.ok) {
2416
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2417
+ }
2418
+ if (!response.body) {
2419
+ throw new Error("Response body is null");
2420
+ }
2421
+ let failedChunk = void 0;
2422
+ const transformStream = new TransformStream({
2423
+ start() {
2424
+ },
2425
+ async transform(chunk, controller) {
2426
+ try {
2427
+ const decoded = new TextDecoder().decode(chunk);
2428
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2429
+ for (const chunk2 of chunks) {
2430
+ if (chunk2) {
2431
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2432
+ try {
2433
+ const parsedChunk = JSON.parse(newChunk);
2434
+ controller.enqueue(parsedChunk);
2435
+ failedChunk = void 0;
2436
+ } catch {
2437
+ failedChunk = newChunk;
2438
+ }
2439
+ }
2440
+ }
2441
+ } catch {
2442
+ }
1555
2443
  }
1556
2444
  });
2445
+ return response.body.pipeThrough(transformStream);
1557
2446
  }
1558
2447
  /**
1559
- * Watches workflow transitions in real-time
1560
- * @param runId - Optional run ID to filter the watch stream
1561
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2448
+ * Watches an existing agent builder action run by runId.
2449
+ * This is used for hot reload recovery - it loads the existing run state
2450
+ * and streams any remaining progress.
2451
+ * This calls `/api/agent-builder/:actionId/watch`.
1562
2452
  */
1563
- async watch({ runId }, onRecord) {
1564
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2453
+ async watch({ runId, eventType }, onRecord) {
2454
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2455
+ const response = await this.request(url, {
2456
+ method: "GET",
1565
2457
  stream: true
1566
2458
  });
1567
2459
  if (!response.ok) {
1568
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2460
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1569
2461
  }
1570
2462
  if (!response.body) {
1571
2463
  throw new Error("Response body is null");
@@ -1579,135 +2471,130 @@ var Workflow = class extends BaseResource {
1579
2471
  }
1580
2472
  }
1581
2473
  /**
1582
- * Creates a new ReadableStream from an iterable or async iterable of objects,
1583
- * serializing each as JSON and separating them with the record separator (\x1E).
1584
- *
1585
- * @param records - An iterable or async iterable of objects to stream
1586
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2474
+ * Gets a specific action run by its ID.
2475
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
1587
2476
  */
1588
- static createRecordStream(records) {
1589
- const encoder = new TextEncoder();
1590
- return new ReadableStream({
1591
- async start(controller) {
1592
- try {
1593
- for await (const record of records) {
1594
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1595
- controller.enqueue(encoder.encode(json));
1596
- }
1597
- controller.close();
1598
- } catch (err) {
1599
- controller.error(err);
1600
- }
1601
- }
2477
+ async runById(runId) {
2478
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2479
+ return this.request(url, {
2480
+ method: "GET"
1602
2481
  });
1603
2482
  }
1604
- };
1605
-
1606
- // src/resources/a2a.ts
1607
- var A2A = class extends BaseResource {
1608
- constructor(options, agentId) {
1609
- super(options);
1610
- this.agentId = agentId;
1611
- }
1612
2483
  /**
1613
- * Get the agent card with metadata about the agent
1614
- * @returns Promise containing the agent card information
2484
+ * Gets details about this agent builder action.
2485
+ * This calls `/api/agent-builder/:actionId`.
1615
2486
  */
1616
- async getCard() {
1617
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2487
+ async details() {
2488
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2489
+ return result;
1618
2490
  }
1619
2491
  /**
1620
- * Send a message to the agent and get a response
1621
- * @param params - Parameters for the task
1622
- * @returns Promise containing the task response
2492
+ * Gets all runs for this agent builder action.
2493
+ * This calls `/api/agent-builder/:actionId/runs`.
1623
2494
  */
1624
- async sendMessage(params) {
1625
- const response = await this.request(`/a2a/${this.agentId}`, {
1626
- method: "POST",
1627
- body: {
1628
- method: "tasks/send",
1629
- params
1630
- }
2495
+ async runs(params) {
2496
+ const searchParams = new URLSearchParams();
2497
+ if (params?.fromDate) {
2498
+ searchParams.set("fromDate", params.fromDate.toISOString());
2499
+ }
2500
+ if (params?.toDate) {
2501
+ searchParams.set("toDate", params.toDate.toISOString());
2502
+ }
2503
+ if (params?.limit !== void 0) {
2504
+ searchParams.set("limit", String(params.limit));
2505
+ }
2506
+ if (params?.offset !== void 0) {
2507
+ searchParams.set("offset", String(params.offset));
2508
+ }
2509
+ if (params?.resourceId) {
2510
+ searchParams.set("resourceId", params.resourceId);
2511
+ }
2512
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2513
+ return this.request(url, {
2514
+ method: "GET"
1631
2515
  });
1632
- return { task: response.result };
1633
2516
  }
1634
2517
  /**
1635
- * Get the status and result of a task
1636
- * @param params - Parameters for querying the task
1637
- * @returns Promise containing the task response
2518
+ * Gets the execution result of an agent builder action run.
2519
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1638
2520
  */
1639
- async getTask(params) {
1640
- const response = await this.request(`/a2a/${this.agentId}`, {
1641
- method: "POST",
1642
- body: {
1643
- method: "tasks/get",
1644
- params
1645
- }
2521
+ async runExecutionResult(runId) {
2522
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2523
+ return this.request(url, {
2524
+ method: "GET"
1646
2525
  });
1647
- return response.result;
1648
2526
  }
1649
2527
  /**
1650
- * Cancel a running task
1651
- * @param params - Parameters identifying the task to cancel
1652
- * @returns Promise containing the task response
2528
+ * Cancels an agent builder action run.
2529
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1653
2530
  */
1654
- async cancelTask(params) {
1655
- return this.request(`/a2a/${this.agentId}`, {
1656
- method: "POST",
1657
- body: {
1658
- method: "tasks/cancel",
1659
- params
1660
- }
2531
+ async cancelRun(runId) {
2532
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2533
+ return this.request(url, {
2534
+ method: "POST"
1661
2535
  });
1662
2536
  }
1663
2537
  /**
1664
- * Send a message and subscribe to streaming updates (not fully implemented)
1665
- * @param params - Parameters for the task
1666
- * @returns Promise containing the task response
2538
+ * Sends an event to an agent builder action run.
2539
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1667
2540
  */
1668
- async sendAndSubscribe(params) {
1669
- return this.request(`/a2a/${this.agentId}`, {
2541
+ async sendRunEvent(params) {
2542
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2543
+ return this.request(url, {
1670
2544
  method: "POST",
1671
- body: {
1672
- method: "tasks/sendSubscribe",
1673
- params
1674
- },
1675
- stream: true
2545
+ body: { event: params.event, data: params.data }
1676
2546
  });
1677
2547
  }
1678
2548
  };
1679
2549
 
1680
- // src/resources/mcp-tool.ts
1681
- var MCPTool = class extends BaseResource {
1682
- serverId;
1683
- toolId;
1684
- constructor(options, serverId, toolId) {
2550
+ // src/resources/observability.ts
2551
+ var Observability = class extends BaseResource {
2552
+ constructor(options) {
1685
2553
  super(options);
1686
- this.serverId = serverId;
1687
- this.toolId = toolId;
1688
2554
  }
1689
2555
  /**
1690
- * Retrieves details about this specific tool from the MCP server.
1691
- * @returns Promise containing the tool's information (name, description, schema).
2556
+ * Retrieves a specific AI trace by ID
2557
+ * @param traceId - ID of the trace to retrieve
2558
+ * @returns Promise containing the AI trace with all its spans
1692
2559
  */
1693
- details() {
1694
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2560
+ getTrace(traceId) {
2561
+ return this.request(`/api/observability/traces/${traceId}`);
1695
2562
  }
1696
2563
  /**
1697
- * Executes this specific tool on the MCP server.
1698
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1699
- * @returns Promise containing the result of the tool execution.
2564
+ * Retrieves paginated list of AI traces with optional filtering
2565
+ * @param params - Parameters for pagination and filtering
2566
+ * @returns Promise containing paginated traces and pagination info
1700
2567
  */
1701
- execute(params) {
1702
- const body = {};
1703
- if (params.data !== void 0) body.data = params.data;
1704
- if (params.runtimeContext !== void 0) {
1705
- body.runtimeContext = params.runtimeContext;
2568
+ getTraces(params) {
2569
+ const { pagination, filters } = params;
2570
+ const { page, perPage, dateRange } = pagination || {};
2571
+ const { name, spanType, entityId, entityType } = filters || {};
2572
+ const searchParams = new URLSearchParams();
2573
+ if (page !== void 0) {
2574
+ searchParams.set("page", String(page));
1706
2575
  }
1707
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1708
- method: "POST",
1709
- body: Object.keys(body).length > 0 ? body : void 0
1710
- });
2576
+ if (perPage !== void 0) {
2577
+ searchParams.set("perPage", String(perPage));
2578
+ }
2579
+ if (name) {
2580
+ searchParams.set("name", name);
2581
+ }
2582
+ if (spanType !== void 0) {
2583
+ searchParams.set("spanType", String(spanType));
2584
+ }
2585
+ if (entityId && entityType) {
2586
+ searchParams.set("entityId", entityId);
2587
+ searchParams.set("entityType", entityType);
2588
+ }
2589
+ if (dateRange) {
2590
+ const dateRangeStr = JSON.stringify({
2591
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2592
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2593
+ });
2594
+ searchParams.set("dateRange", dateRangeStr);
2595
+ }
2596
+ const queryString = searchParams.toString();
2597
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
1711
2598
  }
1712
2599
  };
1713
2600
 
@@ -1775,7 +2662,7 @@ var NetworkMemoryThread = class extends BaseResource {
1775
2662
  };
1776
2663
 
1777
2664
  // src/resources/vNextNetwork.ts
1778
- var RECORD_SEPARATOR3 = "";
2665
+ var RECORD_SEPARATOR4 = "";
1779
2666
  var VNextNetwork = class extends BaseResource {
1780
2667
  constructor(options, networkId) {
1781
2668
  super(options);
@@ -1827,7 +2714,7 @@ var VNextNetwork = class extends BaseResource {
1827
2714
  if (done && !value) continue;
1828
2715
  try {
1829
2716
  const decoded = value ? new TextDecoder().decode(value) : "";
1830
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2717
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
1831
2718
  buffer = chunks.pop() || "";
1832
2719
  for (const chunk of chunks) {
1833
2720
  if (chunk) {
@@ -1914,8 +2801,10 @@ var VNextNetwork = class extends BaseResource {
1914
2801
 
1915
2802
  // src/client.ts
1916
2803
  var MastraClient = class extends BaseResource {
2804
+ observability;
1917
2805
  constructor(options) {
1918
2806
  super(options);
2807
+ this.observability = new Observability(options);
1919
2808
  }
1920
2809
  /**
1921
2810
  * Retrieves all available agents
@@ -1924,21 +2813,6 @@ var MastraClient = class extends BaseResource {
1924
2813
  getAgents() {
1925
2814
  return this.request("/api/agents");
1926
2815
  }
1927
- async getAGUI({ resourceId }) {
1928
- const agents = await this.getAgents();
1929
- return Object.entries(agents).reduce(
1930
- (acc, [agentId]) => {
1931
- const agent = this.getAgent(agentId);
1932
- acc[agentId] = new AGUIAdapter({
1933
- agentId,
1934
- agent,
1935
- resourceId
1936
- });
1937
- return acc;
1938
- },
1939
- {}
1940
- );
1941
- }
1942
2816
  /**
1943
2817
  * Gets an agent instance by ID
1944
2818
  * @param agentId - ID of the agent to retrieve
@@ -2044,7 +2918,7 @@ var MastraClient = class extends BaseResource {
2044
2918
  * @returns Tool instance
2045
2919
  */
2046
2920
  getTool(toolId) {
2047
- return new Tool2(this.options, toolId);
2921
+ return new Tool(this.options, toolId);
2048
2922
  }
2049
2923
  /**
2050
2924
  * Retrieves all available legacy workflows
@@ -2076,6 +2950,20 @@ var MastraClient = class extends BaseResource {
2076
2950
  getWorkflow(workflowId) {
2077
2951
  return new Workflow(this.options, workflowId);
2078
2952
  }
2953
+ /**
2954
+ * Gets all available agent builder actions
2955
+ * @returns Promise containing map of action IDs to action details
2956
+ */
2957
+ getAgentBuilderActions() {
2958
+ return this.request("/api/agent-builder/");
2959
+ }
2960
+ /**
2961
+ * Gets an agent builder instance for executing agent-builder workflows
2962
+ * @returns AgentBuilder instance
2963
+ */
2964
+ getAgentBuilderAction(actionId) {
2965
+ return new AgentBuilder(this.options, actionId);
2966
+ }
2079
2967
  /**
2080
2968
  * Gets a vector instance by name
2081
2969
  * @param vectorName - Name of the vector to retrieve
@@ -2419,6 +3307,19 @@ var MastraClient = class extends BaseResource {
2419
3307
  body: params
2420
3308
  });
2421
3309
  }
3310
+ /**
3311
+ * Retrieves model providers with available keys
3312
+ * @returns Promise containing model providers with available keys
3313
+ */
3314
+ getModelProviders() {
3315
+ return this.request(`/api/model-providers`);
3316
+ }
3317
+ getAITrace(traceId) {
3318
+ return this.observability.getTrace(traceId);
3319
+ }
3320
+ getAITraces(params) {
3321
+ return this.observability.getTraces(params);
3322
+ }
2422
3323
  };
2423
3324
 
2424
3325
  export { MastraClient };