@mastra/client-js 0.0.0-fix-message-list-args-missing-20250807205055 → 0.0.0-fix-zod-to-json-schema-ref-strategy-20250910193441

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 +512 -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 +1235 -376
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.js +1237 -378
  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 +50 -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 +42 -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 +7 -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 -15
  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,42 @@ function processClientTools(clientTools) {
240
58
  );
241
59
  }
242
60
 
61
+ // src/utils/process-mastra-stream.ts
62
+ async function processMastraStream({
63
+ stream,
64
+ onChunk
65
+ }) {
66
+ const reader = stream.getReader();
67
+ const decoder = new TextDecoder();
68
+ let buffer = "";
69
+ try {
70
+ while (true) {
71
+ const { done, value } = await reader.read();
72
+ if (done) break;
73
+ buffer += decoder.decode(value, { stream: true });
74
+ const lines = buffer.split("\n\n");
75
+ buffer = lines.pop() || "";
76
+ for (const line of lines) {
77
+ if (line.startsWith("data: ")) {
78
+ const data = line.slice(6);
79
+ if (data === "[DONE]") {
80
+ console.log("\u{1F3C1} Stream finished");
81
+ return;
82
+ }
83
+ try {
84
+ const json = JSON.parse(data);
85
+ await onChunk(json);
86
+ } catch (error) {
87
+ console.error("\u274C JSON parse error:", error, "Data:", data);
88
+ }
89
+ }
90
+ }
91
+ }
92
+ } finally {
93
+ reader.releaseLock();
94
+ }
95
+ }
96
+
243
97
  // src/resources/base.ts
244
98
  var BaseResource = class {
245
99
  options;
@@ -254,7 +108,7 @@ var BaseResource = class {
254
108
  */
255
109
  async request(path, options = {}) {
256
110
  let lastError = null;
257
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
111
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
258
112
  let delay = backoffMs;
259
113
  for (let attempt = 0; attempt <= retries; attempt++) {
260
114
  try {
@@ -268,6 +122,7 @@ var BaseResource = class {
268
122
  // 'x-mastra-client-type': 'js',
269
123
  },
270
124
  signal: this.options.abortSignal,
125
+ credentials: options.credentials ?? credentials,
271
126
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
272
127
  });
273
128
  if (!response.ok) {
@@ -300,14 +155,64 @@ var BaseResource = class {
300
155
  throw lastError || new Error("Request failed");
301
156
  }
302
157
  };
303
- function parseClientRuntimeContext(runtimeContext) {
304
- if (runtimeContext) {
305
- if (runtimeContext instanceof RuntimeContext) {
306
- return Object.fromEntries(runtimeContext.entries());
158
+
159
+ // src/resources/agent.ts
160
+ async function executeToolCallAndRespond({
161
+ response,
162
+ params,
163
+ runId,
164
+ resourceId,
165
+ threadId,
166
+ runtimeContext,
167
+ respondFn
168
+ }) {
169
+ if (response.finishReason === "tool-calls") {
170
+ const toolCalls = response.toolCalls;
171
+ if (!toolCalls || !Array.isArray(toolCalls)) {
172
+ return response;
173
+ }
174
+ for (const toolCall of toolCalls) {
175
+ const clientTool = params.clientTools?.[toolCall.toolName];
176
+ if (clientTool && clientTool.execute) {
177
+ const result = await clientTool.execute(
178
+ {
179
+ context: toolCall?.args,
180
+ runId,
181
+ resourceId,
182
+ threadId,
183
+ runtimeContext,
184
+ tracingContext: { currentSpan: void 0 }
185
+ },
186
+ {
187
+ messages: response.messages,
188
+ toolCallId: toolCall?.toolCallId
189
+ }
190
+ );
191
+ const updatedMessages = [
192
+ {
193
+ role: "user",
194
+ content: params.messages
195
+ },
196
+ ...response.response.messages,
197
+ {
198
+ role: "tool",
199
+ content: [
200
+ {
201
+ type: "tool-result",
202
+ toolCallId: toolCall.toolCallId,
203
+ toolName: toolCall.toolName,
204
+ result
205
+ }
206
+ ]
207
+ }
208
+ ];
209
+ return respondFn({
210
+ ...params,
211
+ messages: updatedMessages
212
+ });
213
+ }
307
214
  }
308
- return runtimeContext;
309
215
  }
310
- return void 0;
311
216
  }
312
217
  var AgentVoice = class extends BaseResource {
313
218
  constructor(options, agentId) {
@@ -378,6 +283,12 @@ var Agent = class extends BaseResource {
378
283
  return this.request(`/api/agents/${this.agentId}`);
379
284
  }
380
285
  async generate(params) {
286
+ console.warn(
287
+ "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."
288
+ );
289
+ return this.generateLegacy(params);
290
+ }
291
+ async generateLegacy(params) {
381
292
  const processedParams = {
382
293
  ...params,
383
294
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -387,7 +298,7 @@ var Agent = class extends BaseResource {
387
298
  };
388
299
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
389
300
  const response = await this.request(
390
- `/api/agents/${this.agentId}/generate`,
301
+ `/api/agents/${this.agentId}/generate-legacy`,
391
302
  {
392
303
  method: "POST",
393
304
  body: processedParams
@@ -402,7 +313,14 @@ var Agent = class extends BaseResource {
402
313
  const clientTool = params.clientTools?.[toolCall.toolName];
403
314
  if (clientTool && clientTool.execute) {
404
315
  const result = await clientTool.execute(
405
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
316
+ {
317
+ context: toolCall?.args,
318
+ runId,
319
+ resourceId,
320
+ threadId,
321
+ runtimeContext,
322
+ tracingContext: { currentSpan: void 0 }
323
+ },
406
324
  {
407
325
  messages: response.messages,
408
326
  toolCallId: toolCall?.toolCallId
@@ -435,6 +353,38 @@ var Agent = class extends BaseResource {
435
353
  }
436
354
  return response;
437
355
  }
356
+ async generateVNext(params) {
357
+ const processedParams = {
358
+ ...params,
359
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
360
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
361
+ clientTools: processClientTools(params.clientTools),
362
+ structuredOutput: params.structuredOutput ? {
363
+ ...params.structuredOutput,
364
+ schema: zodToJsonSchema(params.structuredOutput.schema)
365
+ } : void 0
366
+ };
367
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
368
+ const response = await this.request(
369
+ `/api/agents/${this.agentId}/generate/vnext`,
370
+ {
371
+ method: "POST",
372
+ body: processedParams
373
+ }
374
+ );
375
+ if (response.finishReason === "tool-calls") {
376
+ return executeToolCallAndRespond({
377
+ response,
378
+ params,
379
+ runId,
380
+ resourceId,
381
+ threadId,
382
+ runtimeContext,
383
+ respondFn: this.generateVNext.bind(this)
384
+ });
385
+ }
386
+ return response;
387
+ }
438
388
  async processChatResponse({
439
389
  stream,
440
390
  update,
@@ -703,6 +653,17 @@ var Agent = class extends BaseResource {
703
653
  * @returns Promise containing the enhanced Response object with processDataStream method
704
654
  */
705
655
  async stream(params) {
656
+ console.warn(
657
+ "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."
658
+ );
659
+ return this.streamLegacy(params);
660
+ }
661
+ /**
662
+ * Streams a response from the agent
663
+ * @param params - Stream parameters including prompt
664
+ * @returns Promise containing the enhanced Response object with processDataStream method
665
+ */
666
+ async streamLegacy(params) {
706
667
  const processedParams = {
707
668
  ...params,
708
669
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -725,11 +686,261 @@ var Agent = class extends BaseResource {
725
686
  };
726
687
  return streamResponse;
727
688
  }
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`, {
689
+ async processChatResponse_vNext({
690
+ stream,
691
+ update,
692
+ onToolCall,
693
+ onFinish,
694
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
695
+ lastMessage
696
+ }) {
697
+ const replaceLastMessage = lastMessage?.role === "assistant";
698
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
699
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
700
+ return Math.max(max, toolInvocation.step ?? 0);
701
+ }, 0) ?? 0) : 0;
702
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
703
+ id: v4(),
704
+ createdAt: getCurrentDate(),
705
+ role: "assistant",
706
+ content: "",
707
+ parts: []
708
+ };
709
+ let currentTextPart = void 0;
710
+ let currentReasoningPart = void 0;
711
+ let currentReasoningTextDetail = void 0;
712
+ function updateToolInvocationPart(toolCallId, invocation) {
713
+ const part = message.parts.find(
714
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
715
+ );
716
+ if (part != null) {
717
+ part.toolInvocation = invocation;
718
+ } else {
719
+ message.parts.push({
720
+ type: "tool-invocation",
721
+ toolInvocation: invocation
722
+ });
723
+ }
724
+ }
725
+ const data = [];
726
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
727
+ const partialToolCalls = {};
728
+ let usage = {
729
+ completionTokens: NaN,
730
+ promptTokens: NaN,
731
+ totalTokens: NaN
732
+ };
733
+ let finishReason = "unknown";
734
+ function execUpdate() {
735
+ const copiedData = [...data];
736
+ if (messageAnnotations?.length) {
737
+ message.annotations = messageAnnotations;
738
+ }
739
+ const copiedMessage = {
740
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
741
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
742
+ ...structuredClone(message),
743
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
744
+ // hashing approach by default to detect changes, but it only works for shallow
745
+ // changes. This is why we need to add a revision id to ensure that the message
746
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
747
+ // forwarded to rendering):
748
+ revisionId: v4()
749
+ };
750
+ update({
751
+ message: copiedMessage,
752
+ data: copiedData,
753
+ replaceLastMessage
754
+ });
755
+ }
756
+ await processMastraStream({
757
+ stream,
758
+ // TODO: casting as any here because the stream types were all typed as any before in core.
759
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
760
+ onChunk: async (chunk) => {
761
+ switch (chunk.type) {
762
+ case "step-start": {
763
+ if (!replaceLastMessage) {
764
+ message.id = chunk.payload.messageId;
765
+ }
766
+ message.parts.push({ type: "step-start" });
767
+ execUpdate();
768
+ break;
769
+ }
770
+ case "text-delta": {
771
+ if (currentTextPart == null) {
772
+ currentTextPart = {
773
+ type: "text",
774
+ text: chunk.payload.text
775
+ };
776
+ message.parts.push(currentTextPart);
777
+ } else {
778
+ currentTextPart.text += chunk.payload.text;
779
+ }
780
+ message.content += chunk.payload.text;
781
+ execUpdate();
782
+ break;
783
+ }
784
+ case "reasoning-delta": {
785
+ if (currentReasoningTextDetail == null) {
786
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
787
+ if (currentReasoningPart != null) {
788
+ currentReasoningPart.details.push(currentReasoningTextDetail);
789
+ }
790
+ } else {
791
+ currentReasoningTextDetail.text += chunk.payload.text;
792
+ }
793
+ if (currentReasoningPart == null) {
794
+ currentReasoningPart = {
795
+ type: "reasoning",
796
+ reasoning: chunk.payload.text,
797
+ details: [currentReasoningTextDetail]
798
+ };
799
+ message.parts.push(currentReasoningPart);
800
+ } else {
801
+ currentReasoningPart.reasoning += chunk.payload.text;
802
+ }
803
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
804
+ execUpdate();
805
+ break;
806
+ }
807
+ case "file": {
808
+ message.parts.push({
809
+ type: "file",
810
+ mimeType: chunk.payload.mimeType,
811
+ data: chunk.payload.data
812
+ });
813
+ execUpdate();
814
+ break;
815
+ }
816
+ case "source": {
817
+ message.parts.push({
818
+ type: "source",
819
+ source: chunk.payload.source
820
+ });
821
+ execUpdate();
822
+ break;
823
+ }
824
+ case "tool-call": {
825
+ const invocation = {
826
+ state: "call",
827
+ step,
828
+ ...chunk.payload
829
+ };
830
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
831
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
832
+ } else {
833
+ if (message.toolInvocations == null) {
834
+ message.toolInvocations = [];
835
+ }
836
+ message.toolInvocations.push(invocation);
837
+ }
838
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
839
+ execUpdate();
840
+ if (onToolCall) {
841
+ const result = await onToolCall({ toolCall: chunk.payload });
842
+ if (result != null) {
843
+ const invocation2 = {
844
+ state: "result",
845
+ step,
846
+ ...chunk.payload,
847
+ result
848
+ };
849
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
850
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
851
+ execUpdate();
852
+ }
853
+ }
854
+ }
855
+ case "tool-call-input-streaming-start": {
856
+ if (message.toolInvocations == null) {
857
+ message.toolInvocations = [];
858
+ }
859
+ partialToolCalls[chunk.payload.toolCallId] = {
860
+ text: "",
861
+ step,
862
+ toolName: chunk.payload.toolName,
863
+ index: message.toolInvocations.length
864
+ };
865
+ const invocation = {
866
+ state: "partial-call",
867
+ step,
868
+ toolCallId: chunk.payload.toolCallId,
869
+ toolName: chunk.payload.toolName,
870
+ args: chunk.payload.args
871
+ };
872
+ message.toolInvocations.push(invocation);
873
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
874
+ execUpdate();
875
+ break;
876
+ }
877
+ case "tool-call-delta": {
878
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
879
+ partialToolCall.text += chunk.payload.argsTextDelta;
880
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
881
+ const invocation = {
882
+ state: "partial-call",
883
+ step: partialToolCall.step,
884
+ toolCallId: chunk.payload.toolCallId,
885
+ toolName: partialToolCall.toolName,
886
+ args: partialArgs
887
+ };
888
+ message.toolInvocations[partialToolCall.index] = invocation;
889
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
890
+ execUpdate();
891
+ break;
892
+ }
893
+ case "tool-result": {
894
+ const toolInvocations = message.toolInvocations;
895
+ if (toolInvocations == null) {
896
+ throw new Error("tool_result must be preceded by a tool_call");
897
+ }
898
+ const toolInvocationIndex = toolInvocations.findIndex(
899
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
900
+ );
901
+ if (toolInvocationIndex === -1) {
902
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
903
+ }
904
+ const invocation = {
905
+ ...toolInvocations[toolInvocationIndex],
906
+ state: "result",
907
+ ...chunk.payload
908
+ };
909
+ toolInvocations[toolInvocationIndex] = invocation;
910
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
911
+ execUpdate();
912
+ break;
913
+ }
914
+ case "error": {
915
+ throw new Error(chunk.payload.error);
916
+ }
917
+ case "data": {
918
+ data.push(...chunk.payload.data);
919
+ execUpdate();
920
+ break;
921
+ }
922
+ case "step-finish": {
923
+ step += 1;
924
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
925
+ currentReasoningPart = void 0;
926
+ currentReasoningTextDetail = void 0;
927
+ execUpdate();
928
+ break;
929
+ }
930
+ case "finish": {
931
+ finishReason = chunk.payload.stepResult.reason;
932
+ if (chunk.payload.usage != null) {
933
+ usage = chunk.payload.usage;
934
+ }
935
+ break;
936
+ }
937
+ }
938
+ }
939
+ });
940
+ onFinish?.({ message, finishReason, usage });
941
+ }
942
+ async processStreamResponse_vNext(processedParams, writable) {
943
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
733
944
  method: "POST",
734
945
  body: processedParams,
735
946
  stream: true
@@ -741,12 +952,31 @@ var Agent = class extends BaseResource {
741
952
  let toolCalls = [];
742
953
  let messages = [];
743
954
  const [streamForWritable, streamForProcessing] = response.body.tee();
744
- streamForWritable.pipeTo(writable, {
745
- preventClose: true
746
- }).catch((error) => {
955
+ streamForWritable.pipeTo(
956
+ new WritableStream({
957
+ async write(chunk) {
958
+ try {
959
+ const text = new TextDecoder().decode(chunk);
960
+ if (text.includes("[DONE]")) {
961
+ return;
962
+ }
963
+ } catch {
964
+ }
965
+ const writer = writable.getWriter();
966
+ try {
967
+ await writer.write(chunk);
968
+ } finally {
969
+ writer.releaseLock();
970
+ }
971
+ }
972
+ }),
973
+ {
974
+ preventClose: true
975
+ }
976
+ ).catch((error) => {
747
977
  console.error("Error piping to writable stream:", error);
748
978
  });
749
- this.processChatResponse({
979
+ this.processChatResponse_vNext({
750
980
  stream: streamForProcessing,
751
981
  update: ({ message }) => {
752
982
  const existingIndex = messages.findIndex((m) => m.id === message.id);
@@ -771,14 +1001,17 @@ var Agent = class extends BaseResource {
771
1001
  runId: processedParams.runId,
772
1002
  resourceId: processedParams.resourceId,
773
1003
  threadId: processedParams.threadId,
774
- runtimeContext: processedParams.runtimeContext
1004
+ runtimeContext: processedParams.runtimeContext,
1005
+ // TODO: Pass proper tracing context when client-js supports tracing
1006
+ tracingContext: { currentSpan: void 0 }
775
1007
  },
776
1008
  {
777
1009
  messages: response.messages,
778
1010
  toolCallId: toolCall2?.toolCallId
779
1011
  }
780
1012
  );
781
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1013
+ const lastMessageRaw = messages[messages.length - 1];
1014
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
782
1015
  const toolInvocationPart = lastMessage?.parts?.find(
783
1016
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
784
1017
  );
@@ -796,13 +1029,143 @@ var Agent = class extends BaseResource {
796
1029
  toolInvocation.state = "result";
797
1030
  toolInvocation.result = result;
798
1031
  }
799
- const writer = writable.getWriter();
800
- try {
801
- await writer.write(
802
- new TextEncoder().encode(
803
- "a:" + JSON.stringify({
804
- toolCallId: toolCall2.toolCallId,
805
- result
1032
+ const originalMessages = processedParams.messages;
1033
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1034
+ const updatedMessages = lastMessage != null ? [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messageArray, ...messages];
1035
+ this.processStreamResponse_vNext(
1036
+ {
1037
+ ...processedParams,
1038
+ messages: updatedMessages
1039
+ },
1040
+ writable
1041
+ ).catch((error) => {
1042
+ console.error("Error processing stream response:", error);
1043
+ });
1044
+ }
1045
+ }
1046
+ } else {
1047
+ setTimeout(() => {
1048
+ writable.close();
1049
+ }, 0);
1050
+ }
1051
+ },
1052
+ lastMessage: void 0
1053
+ }).catch((error) => {
1054
+ console.error("Error processing stream response:", error);
1055
+ });
1056
+ } catch (error) {
1057
+ console.error("Error processing stream response:", error);
1058
+ }
1059
+ return response;
1060
+ }
1061
+ async streamVNext(params) {
1062
+ const processedParams = {
1063
+ ...params,
1064
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1065
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1066
+ clientTools: processClientTools(params.clientTools),
1067
+ structuredOutput: params.structuredOutput ? {
1068
+ ...params.structuredOutput,
1069
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1070
+ } : void 0
1071
+ };
1072
+ const { readable, writable } = new TransformStream();
1073
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1074
+ const streamResponse = new Response(readable, {
1075
+ status: response.status,
1076
+ statusText: response.statusText,
1077
+ headers: response.headers
1078
+ });
1079
+ streamResponse.processDataStream = async ({
1080
+ onChunk
1081
+ }) => {
1082
+ await processMastraStream({
1083
+ stream: streamResponse.body,
1084
+ onChunk
1085
+ });
1086
+ };
1087
+ return streamResponse;
1088
+ }
1089
+ /**
1090
+ * Processes the stream response and handles tool calls
1091
+ */
1092
+ async processStreamResponse(processedParams, writable) {
1093
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1094
+ method: "POST",
1095
+ body: processedParams,
1096
+ stream: true
1097
+ });
1098
+ if (!response.body) {
1099
+ throw new Error("No response body");
1100
+ }
1101
+ try {
1102
+ let toolCalls = [];
1103
+ let messages = [];
1104
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1105
+ streamForWritable.pipeTo(writable, {
1106
+ preventClose: true
1107
+ }).catch((error) => {
1108
+ console.error("Error piping to writable stream:", error);
1109
+ });
1110
+ this.processChatResponse({
1111
+ stream: streamForProcessing,
1112
+ update: ({ message }) => {
1113
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1114
+ if (existingIndex !== -1) {
1115
+ messages[existingIndex] = message;
1116
+ } else {
1117
+ messages.push(message);
1118
+ }
1119
+ },
1120
+ onFinish: async ({ finishReason, message }) => {
1121
+ if (finishReason === "tool-calls") {
1122
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1123
+ if (toolCall) {
1124
+ toolCalls.push(toolCall);
1125
+ }
1126
+ for (const toolCall2 of toolCalls) {
1127
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1128
+ if (clientTool && clientTool.execute) {
1129
+ const result = await clientTool.execute(
1130
+ {
1131
+ context: toolCall2?.args,
1132
+ runId: processedParams.runId,
1133
+ resourceId: processedParams.resourceId,
1134
+ threadId: processedParams.threadId,
1135
+ runtimeContext: processedParams.runtimeContext,
1136
+ // TODO: Pass proper tracing context when client-js supports tracing
1137
+ tracingContext: { currentSpan: void 0 }
1138
+ },
1139
+ {
1140
+ messages: response.messages,
1141
+ toolCallId: toolCall2?.toolCallId
1142
+ }
1143
+ );
1144
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1145
+ const toolInvocationPart = lastMessage?.parts?.find(
1146
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1147
+ );
1148
+ if (toolInvocationPart) {
1149
+ toolInvocationPart.toolInvocation = {
1150
+ ...toolInvocationPart.toolInvocation,
1151
+ state: "result",
1152
+ result
1153
+ };
1154
+ }
1155
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1156
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1157
+ );
1158
+ if (toolInvocation) {
1159
+ toolInvocation.state = "result";
1160
+ toolInvocation.result = result;
1161
+ }
1162
+ const writer = writable.getWriter();
1163
+ try {
1164
+ await writer.write(
1165
+ new TextEncoder().encode(
1166
+ "a:" + JSON.stringify({
1167
+ toolCallId: toolCall2.toolCallId,
1168
+ result
806
1169
  }) + "\n"
807
1170
  )
808
1171
  );
@@ -875,6 +1238,17 @@ var Agent = class extends BaseResource {
875
1238
  liveEvals() {
876
1239
  return this.request(`/api/agents/${this.agentId}/evals/live`);
877
1240
  }
1241
+ /**
1242
+ * Updates the model for the agent
1243
+ * @param params - Parameters for updating the model
1244
+ * @returns Promise containing the updated model
1245
+ */
1246
+ updateModel(params) {
1247
+ return this.request(`/api/agents/${this.agentId}/model`, {
1248
+ method: "POST",
1249
+ body: params
1250
+ });
1251
+ }
878
1252
  };
879
1253
  var Network = class extends BaseResource {
880
1254
  constructor(options, networkId) {
@@ -1259,7 +1633,7 @@ var LegacyWorkflow = class extends BaseResource {
1259
1633
  };
1260
1634
 
1261
1635
  // src/resources/tool.ts
1262
- var Tool2 = class extends BaseResource {
1636
+ var Tool = class extends BaseResource {
1263
1637
  constructor(options, toolId) {
1264
1638
  super(options);
1265
1639
  this.toolId = toolId;
@@ -1483,32 +1857,472 @@ var Workflow = class extends BaseResource {
1483
1857
  searchParams.set("runId", params.runId);
1484
1858
  }
1485
1859
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1486
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1860
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1861
+ method: "POST",
1862
+ body: { inputData: params.inputData, runtimeContext }
1863
+ });
1864
+ }
1865
+ /**
1866
+ * Starts a workflow run and returns a stream
1867
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1868
+ * @returns Promise containing the workflow execution results
1869
+ */
1870
+ async stream(params) {
1871
+ const searchParams = new URLSearchParams();
1872
+ if (!!params?.runId) {
1873
+ searchParams.set("runId", params.runId);
1874
+ }
1875
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1876
+ const response = await this.request(
1877
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1878
+ {
1879
+ method: "POST",
1880
+ body: { inputData: params.inputData, runtimeContext },
1881
+ stream: true
1882
+ }
1883
+ );
1884
+ if (!response.ok) {
1885
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1886
+ }
1887
+ if (!response.body) {
1888
+ throw new Error("Response body is null");
1889
+ }
1890
+ let failedChunk = void 0;
1891
+ const transformStream = new TransformStream({
1892
+ start() {
1893
+ },
1894
+ async transform(chunk, controller) {
1895
+ try {
1896
+ const decoded = new TextDecoder().decode(chunk);
1897
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1898
+ for (const chunk2 of chunks) {
1899
+ if (chunk2) {
1900
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1901
+ try {
1902
+ const parsedChunk = JSON.parse(newChunk);
1903
+ controller.enqueue(parsedChunk);
1904
+ failedChunk = void 0;
1905
+ } catch {
1906
+ failedChunk = newChunk;
1907
+ }
1908
+ }
1909
+ }
1910
+ } catch {
1911
+ }
1912
+ }
1913
+ });
1914
+ return response.body.pipeThrough(transformStream);
1915
+ }
1916
+ /**
1917
+ * Starts a workflow run and returns a stream
1918
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1919
+ * @returns Promise containing the workflow execution results
1920
+ */
1921
+ async streamVNext(params) {
1922
+ const searchParams = new URLSearchParams();
1923
+ if (!!params?.runId) {
1924
+ searchParams.set("runId", params.runId);
1925
+ }
1926
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1927
+ const response = await this.request(
1928
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1929
+ {
1930
+ method: "POST",
1931
+ body: { inputData: params.inputData, runtimeContext },
1932
+ stream: true
1933
+ }
1934
+ );
1935
+ if (!response.ok) {
1936
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1937
+ }
1938
+ if (!response.body) {
1939
+ throw new Error("Response body is null");
1940
+ }
1941
+ let failedChunk = void 0;
1942
+ const transformStream = new TransformStream({
1943
+ start() {
1944
+ },
1945
+ async transform(chunk, controller) {
1946
+ try {
1947
+ const decoded = new TextDecoder().decode(chunk);
1948
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1949
+ for (const chunk2 of chunks) {
1950
+ if (chunk2) {
1951
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1952
+ try {
1953
+ const parsedChunk = JSON.parse(newChunk);
1954
+ controller.enqueue(parsedChunk);
1955
+ failedChunk = void 0;
1956
+ } catch {
1957
+ failedChunk = newChunk;
1958
+ }
1959
+ }
1960
+ }
1961
+ } catch {
1962
+ }
1963
+ }
1964
+ });
1965
+ return response.body.pipeThrough(transformStream);
1966
+ }
1967
+ /**
1968
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1969
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1970
+ * @returns Promise containing the workflow resume results
1971
+ */
1972
+ resumeAsync(params) {
1973
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1974
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1975
+ method: "POST",
1976
+ body: {
1977
+ step: params.step,
1978
+ resumeData: params.resumeData,
1979
+ runtimeContext
1980
+ }
1981
+ });
1982
+ }
1983
+ /**
1984
+ * Watches workflow transitions in real-time
1985
+ * @param runId - Optional run ID to filter the watch stream
1986
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1987
+ */
1988
+ async watch({ runId }, onRecord) {
1989
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1990
+ stream: true
1991
+ });
1992
+ if (!response.ok) {
1993
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1994
+ }
1995
+ if (!response.body) {
1996
+ throw new Error("Response body is null");
1997
+ }
1998
+ for await (const record of this.streamProcessor(response.body)) {
1999
+ if (typeof record === "string") {
2000
+ onRecord(JSON.parse(record));
2001
+ } else {
2002
+ onRecord(record);
2003
+ }
2004
+ }
2005
+ }
2006
+ /**
2007
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2008
+ * serializing each as JSON and separating them with the record separator (\x1E).
2009
+ *
2010
+ * @param records - An iterable or async iterable of objects to stream
2011
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2012
+ */
2013
+ static createRecordStream(records) {
2014
+ const encoder = new TextEncoder();
2015
+ return new ReadableStream({
2016
+ async start(controller) {
2017
+ try {
2018
+ for await (const record of records) {
2019
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2020
+ controller.enqueue(encoder.encode(json));
2021
+ }
2022
+ controller.close();
2023
+ } catch (err) {
2024
+ controller.error(err);
2025
+ }
2026
+ }
2027
+ });
2028
+ }
2029
+ };
2030
+
2031
+ // src/resources/a2a.ts
2032
+ var A2A = class extends BaseResource {
2033
+ constructor(options, agentId) {
2034
+ super(options);
2035
+ this.agentId = agentId;
2036
+ }
2037
+ /**
2038
+ * Get the agent card with metadata about the agent
2039
+ * @returns Promise containing the agent card information
2040
+ */
2041
+ async getCard() {
2042
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2043
+ }
2044
+ /**
2045
+ * Send a message to the agent and gets a message or task response
2046
+ * @param params - Parameters for the task
2047
+ * @returns Promise containing the response
2048
+ */
2049
+ async sendMessage(params) {
2050
+ const response = await this.request(`/a2a/${this.agentId}`, {
2051
+ method: "POST",
2052
+ body: {
2053
+ method: "message/send",
2054
+ params
2055
+ }
2056
+ });
2057
+ return response;
2058
+ }
2059
+ /**
2060
+ * Sends a message to an agent to initiate/continue a task and subscribes
2061
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2062
+ * @param params - Parameters for the task
2063
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2064
+ */
2065
+ async sendStreamingMessage(params) {
2066
+ const response = await this.request(`/a2a/${this.agentId}`, {
2067
+ method: "POST",
2068
+ body: {
2069
+ method: "message/stream",
2070
+ params
2071
+ }
2072
+ });
2073
+ return response;
2074
+ }
2075
+ /**
2076
+ * Get the status and result of a task
2077
+ * @param params - Parameters for querying the task
2078
+ * @returns Promise containing the task response
2079
+ */
2080
+ async getTask(params) {
2081
+ const response = await this.request(`/a2a/${this.agentId}`, {
2082
+ method: "POST",
2083
+ body: {
2084
+ method: "tasks/get",
2085
+ params
2086
+ }
2087
+ });
2088
+ return response;
2089
+ }
2090
+ /**
2091
+ * Cancel a running task
2092
+ * @param params - Parameters identifying the task to cancel
2093
+ * @returns Promise containing the task response
2094
+ */
2095
+ async cancelTask(params) {
2096
+ return this.request(`/a2a/${this.agentId}`, {
2097
+ method: "POST",
2098
+ body: {
2099
+ method: "tasks/cancel",
2100
+ params
2101
+ }
2102
+ });
2103
+ }
2104
+ };
2105
+
2106
+ // src/resources/mcp-tool.ts
2107
+ var MCPTool = class extends BaseResource {
2108
+ serverId;
2109
+ toolId;
2110
+ constructor(options, serverId, toolId) {
2111
+ super(options);
2112
+ this.serverId = serverId;
2113
+ this.toolId = toolId;
2114
+ }
2115
+ /**
2116
+ * Retrieves details about this specific tool from the MCP server.
2117
+ * @returns Promise containing the tool's information (name, description, schema).
2118
+ */
2119
+ details() {
2120
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2121
+ }
2122
+ /**
2123
+ * Executes this specific tool on the MCP server.
2124
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2125
+ * @returns Promise containing the result of the tool execution.
2126
+ */
2127
+ execute(params) {
2128
+ const body = {};
2129
+ if (params.data !== void 0) body.data = params.data;
2130
+ if (params.runtimeContext !== void 0) {
2131
+ body.runtimeContext = params.runtimeContext;
2132
+ }
2133
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2134
+ method: "POST",
2135
+ body: Object.keys(body).length > 0 ? body : void 0
2136
+ });
2137
+ }
2138
+ };
2139
+
2140
+ // src/resources/agent-builder.ts
2141
+ var RECORD_SEPARATOR3 = "";
2142
+ var AgentBuilder = class extends BaseResource {
2143
+ constructor(options, actionId) {
2144
+ super(options);
2145
+ this.actionId = actionId;
2146
+ }
2147
+ // Helper function to transform workflow result to action result
2148
+ transformWorkflowResult(result) {
2149
+ if (result.status === "success") {
2150
+ return {
2151
+ success: result.result.success || false,
2152
+ applied: result.result.applied || false,
2153
+ branchName: result.result.branchName,
2154
+ message: result.result.message || "Agent builder action completed",
2155
+ validationResults: result.result.validationResults,
2156
+ error: result.result.error,
2157
+ errors: result.result.errors,
2158
+ stepResults: result.result.stepResults
2159
+ };
2160
+ } else if (result.status === "failed") {
2161
+ return {
2162
+ success: false,
2163
+ applied: false,
2164
+ message: `Agent builder action failed: ${result.error.message}`,
2165
+ error: result.error.message
2166
+ };
2167
+ } else {
2168
+ return {
2169
+ success: false,
2170
+ applied: false,
2171
+ message: "Agent builder action was suspended",
2172
+ error: "Workflow suspended - manual intervention required"
2173
+ };
2174
+ }
2175
+ }
2176
+ /**
2177
+ * Creates a new agent builder action run and returns the runId.
2178
+ * This calls `/api/agent-builder/:actionId/create-run`.
2179
+ */
2180
+ async createRun(params) {
2181
+ const searchParams = new URLSearchParams();
2182
+ if (!!params?.runId) {
2183
+ searchParams.set("runId", params.runId);
2184
+ }
2185
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2186
+ return this.request(url, {
2187
+ method: "POST"
2188
+ });
2189
+ }
2190
+ /**
2191
+ * Creates a new workflow run (alias for createRun)
2192
+ * @param params - Optional object containing the optional runId
2193
+ * @returns Promise containing the runId of the created run
2194
+ */
2195
+ createRunAsync(params) {
2196
+ return this.createRun(params);
2197
+ }
2198
+ /**
2199
+ * Starts agent builder action asynchronously and waits for completion.
2200
+ * This calls `/api/agent-builder/:actionId/start-async`.
2201
+ */
2202
+ async startAsync(params, runId) {
2203
+ const searchParams = new URLSearchParams();
2204
+ if (runId) {
2205
+ searchParams.set("runId", runId);
2206
+ }
2207
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2208
+ const { runtimeContext: _, ...actionParams } = params;
2209
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2210
+ const result = await this.request(url, {
2211
+ method: "POST",
2212
+ body: { ...actionParams, runtimeContext }
2213
+ });
2214
+ return this.transformWorkflowResult(result);
2215
+ }
2216
+ /**
2217
+ * Starts an existing agent builder action run.
2218
+ * This calls `/api/agent-builder/:actionId/start`.
2219
+ */
2220
+ async startActionRun(params, runId) {
2221
+ const searchParams = new URLSearchParams();
2222
+ searchParams.set("runId", runId);
2223
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2224
+ const { runtimeContext: _, ...actionParams } = params;
2225
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2226
+ return this.request(url, {
2227
+ method: "POST",
2228
+ body: { ...actionParams, runtimeContext }
2229
+ });
2230
+ }
2231
+ /**
2232
+ * Resumes a suspended agent builder action step.
2233
+ * This calls `/api/agent-builder/:actionId/resume`.
2234
+ */
2235
+ async resume(params, runId) {
2236
+ const searchParams = new URLSearchParams();
2237
+ searchParams.set("runId", runId);
2238
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2239
+ const { runtimeContext: _, ...resumeParams } = params;
2240
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2241
+ return this.request(url, {
2242
+ method: "POST",
2243
+ body: { ...resumeParams, runtimeContext }
2244
+ });
2245
+ }
2246
+ /**
2247
+ * Resumes a suspended agent builder action step asynchronously.
2248
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2249
+ */
2250
+ async resumeAsync(params, runId) {
2251
+ const searchParams = new URLSearchParams();
2252
+ searchParams.set("runId", runId);
2253
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2254
+ const { runtimeContext: _, ...resumeParams } = params;
2255
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2256
+ const result = await this.request(url, {
1487
2257
  method: "POST",
1488
- body: { inputData: params.inputData, runtimeContext }
2258
+ body: { ...resumeParams, runtimeContext }
1489
2259
  });
2260
+ return this.transformWorkflowResult(result);
1490
2261
  }
1491
2262
  /**
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
2263
+ * Creates an async generator that processes a readable stream and yields action records
2264
+ * separated by the Record Separator character (\x1E)
2265
+ *
2266
+ * @param stream - The readable stream to process
2267
+ * @returns An async generator that yields parsed records
1495
2268
  */
1496
- async stream(params) {
2269
+ async *streamProcessor(stream) {
2270
+ const reader = stream.getReader();
2271
+ let doneReading = false;
2272
+ let buffer = "";
2273
+ try {
2274
+ while (!doneReading) {
2275
+ const { done, value } = await reader.read();
2276
+ doneReading = done;
2277
+ if (done && !value) continue;
2278
+ try {
2279
+ const decoded = value ? new TextDecoder().decode(value) : "";
2280
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2281
+ buffer = chunks.pop() || "";
2282
+ for (const chunk of chunks) {
2283
+ if (chunk) {
2284
+ if (typeof chunk === "string") {
2285
+ try {
2286
+ const parsedChunk = JSON.parse(chunk);
2287
+ yield parsedChunk;
2288
+ } catch {
2289
+ }
2290
+ }
2291
+ }
2292
+ }
2293
+ } catch {
2294
+ }
2295
+ }
2296
+ if (buffer) {
2297
+ try {
2298
+ yield JSON.parse(buffer);
2299
+ } catch {
2300
+ }
2301
+ }
2302
+ } finally {
2303
+ reader.cancel().catch(() => {
2304
+ });
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Streams agent builder action progress in real-time.
2309
+ * This calls `/api/agent-builder/:actionId/stream`.
2310
+ */
2311
+ async stream(params, runId) {
1497
2312
  const searchParams = new URLSearchParams();
1498
- if (!!params?.runId) {
1499
- searchParams.set("runId", params.runId);
2313
+ if (runId) {
2314
+ searchParams.set("runId", runId);
1500
2315
  }
1501
2316
  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
- );
2317
+ const { runtimeContext: _, ...actionParams } = params;
2318
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2319
+ const response = await this.request(url, {
2320
+ method: "POST",
2321
+ body: { ...actionParams, runtimeContext },
2322
+ stream: true
2323
+ });
1510
2324
  if (!response.ok) {
1511
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2325
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1512
2326
  }
1513
2327
  if (!response.body) {
1514
2328
  throw new Error("Response body is null");
@@ -1520,7 +2334,7 @@ var Workflow = class extends BaseResource {
1520
2334
  async transform(chunk, controller) {
1521
2335
  try {
1522
2336
  const decoded = new TextDecoder().decode(chunk);
1523
- const chunks = decoded.split(RECORD_SEPARATOR2);
2337
+ const chunks = decoded.split(RECORD_SEPARATOR3);
1524
2338
  for (const chunk2 of chunks) {
1525
2339
  if (chunk2) {
1526
2340
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1528,7 +2342,7 @@ var Workflow = class extends BaseResource {
1528
2342
  const parsedChunk = JSON.parse(newChunk);
1529
2343
  controller.enqueue(parsedChunk);
1530
2344
  failedChunk = void 0;
1531
- } catch (error) {
2345
+ } catch {
1532
2346
  failedChunk = newChunk;
1533
2347
  }
1534
2348
  }
@@ -1540,32 +2354,68 @@ var Workflow = class extends BaseResource {
1540
2354
  return response.body.pipeThrough(transformStream);
1541
2355
  }
1542
2356
  /**
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
2357
+ * Streams agent builder action progress in real-time using VNext streaming.
2358
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1546
2359
  */
1547
- resumeAsync(params) {
2360
+ async streamVNext(params, runId) {
2361
+ const searchParams = new URLSearchParams();
2362
+ if (runId) {
2363
+ searchParams.set("runId", runId);
2364
+ }
1548
2365
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1549
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2366
+ const { runtimeContext: _, ...actionParams } = params;
2367
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2368
+ const response = await this.request(url, {
1550
2369
  method: "POST",
1551
- body: {
1552
- step: params.step,
1553
- resumeData: params.resumeData,
1554
- runtimeContext
2370
+ body: { ...actionParams, runtimeContext },
2371
+ stream: true
2372
+ });
2373
+ if (!response.ok) {
2374
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2375
+ }
2376
+ if (!response.body) {
2377
+ throw new Error("Response body is null");
2378
+ }
2379
+ let failedChunk = void 0;
2380
+ const transformStream = new TransformStream({
2381
+ start() {
2382
+ },
2383
+ async transform(chunk, controller) {
2384
+ try {
2385
+ const decoded = new TextDecoder().decode(chunk);
2386
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2387
+ for (const chunk2 of chunks) {
2388
+ if (chunk2) {
2389
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2390
+ try {
2391
+ const parsedChunk = JSON.parse(newChunk);
2392
+ controller.enqueue(parsedChunk);
2393
+ failedChunk = void 0;
2394
+ } catch {
2395
+ failedChunk = newChunk;
2396
+ }
2397
+ }
2398
+ }
2399
+ } catch {
2400
+ }
1555
2401
  }
1556
2402
  });
2403
+ return response.body.pipeThrough(transformStream);
1557
2404
  }
1558
2405
  /**
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
2406
+ * Watches an existing agent builder action run by runId.
2407
+ * This is used for hot reload recovery - it loads the existing run state
2408
+ * and streams any remaining progress.
2409
+ * This calls `/api/agent-builder/:actionId/watch`.
1562
2410
  */
1563
- async watch({ runId }, onRecord) {
1564
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2411
+ async watch({ runId, eventType }, onRecord) {
2412
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2413
+ const response = await this.request(url, {
2414
+ method: "GET",
1565
2415
  stream: true
1566
2416
  });
1567
2417
  if (!response.ok) {
1568
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2418
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1569
2419
  }
1570
2420
  if (!response.body) {
1571
2421
  throw new Error("Response body is null");
@@ -1579,135 +2429,130 @@ var Workflow = class extends BaseResource {
1579
2429
  }
1580
2430
  }
1581
2431
  /**
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
2432
+ * Gets a specific action run by its ID.
2433
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
1587
2434
  */
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
- }
2435
+ async runById(runId) {
2436
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2437
+ return this.request(url, {
2438
+ method: "GET"
1602
2439
  });
1603
2440
  }
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
2441
  /**
1613
- * Get the agent card with metadata about the agent
1614
- * @returns Promise containing the agent card information
2442
+ * Gets details about this agent builder action.
2443
+ * This calls `/api/agent-builder/:actionId`.
1615
2444
  */
1616
- async getCard() {
1617
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2445
+ async details() {
2446
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2447
+ return result;
1618
2448
  }
1619
2449
  /**
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
2450
+ * Gets all runs for this agent builder action.
2451
+ * This calls `/api/agent-builder/:actionId/runs`.
1623
2452
  */
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
- }
2453
+ async runs(params) {
2454
+ const searchParams = new URLSearchParams();
2455
+ if (params?.fromDate) {
2456
+ searchParams.set("fromDate", params.fromDate.toISOString());
2457
+ }
2458
+ if (params?.toDate) {
2459
+ searchParams.set("toDate", params.toDate.toISOString());
2460
+ }
2461
+ if (params?.limit !== void 0) {
2462
+ searchParams.set("limit", String(params.limit));
2463
+ }
2464
+ if (params?.offset !== void 0) {
2465
+ searchParams.set("offset", String(params.offset));
2466
+ }
2467
+ if (params?.resourceId) {
2468
+ searchParams.set("resourceId", params.resourceId);
2469
+ }
2470
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2471
+ return this.request(url, {
2472
+ method: "GET"
1631
2473
  });
1632
- return { task: response.result };
1633
2474
  }
1634
2475
  /**
1635
- * Get the status and result of a task
1636
- * @param params - Parameters for querying the task
1637
- * @returns Promise containing the task response
2476
+ * Gets the execution result of an agent builder action run.
2477
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1638
2478
  */
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
- }
2479
+ async runExecutionResult(runId) {
2480
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2481
+ return this.request(url, {
2482
+ method: "GET"
1646
2483
  });
1647
- return response.result;
1648
2484
  }
1649
2485
  /**
1650
- * Cancel a running task
1651
- * @param params - Parameters identifying the task to cancel
1652
- * @returns Promise containing the task response
2486
+ * Cancels an agent builder action run.
2487
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1653
2488
  */
1654
- async cancelTask(params) {
1655
- return this.request(`/a2a/${this.agentId}`, {
1656
- method: "POST",
1657
- body: {
1658
- method: "tasks/cancel",
1659
- params
1660
- }
2489
+ async cancelRun(runId) {
2490
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2491
+ return this.request(url, {
2492
+ method: "POST"
1661
2493
  });
1662
2494
  }
1663
2495
  /**
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
2496
+ * Sends an event to an agent builder action run.
2497
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1667
2498
  */
1668
- async sendAndSubscribe(params) {
1669
- return this.request(`/a2a/${this.agentId}`, {
2499
+ async sendRunEvent(params) {
2500
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2501
+ return this.request(url, {
1670
2502
  method: "POST",
1671
- body: {
1672
- method: "tasks/sendSubscribe",
1673
- params
1674
- },
1675
- stream: true
2503
+ body: { event: params.event, data: params.data }
1676
2504
  });
1677
2505
  }
1678
2506
  };
1679
2507
 
1680
- // src/resources/mcp-tool.ts
1681
- var MCPTool = class extends BaseResource {
1682
- serverId;
1683
- toolId;
1684
- constructor(options, serverId, toolId) {
2508
+ // src/resources/observability.ts
2509
+ var Observability = class extends BaseResource {
2510
+ constructor(options) {
1685
2511
  super(options);
1686
- this.serverId = serverId;
1687
- this.toolId = toolId;
1688
2512
  }
1689
2513
  /**
1690
- * Retrieves details about this specific tool from the MCP server.
1691
- * @returns Promise containing the tool's information (name, description, schema).
2514
+ * Retrieves a specific AI trace by ID
2515
+ * @param traceId - ID of the trace to retrieve
2516
+ * @returns Promise containing the AI trace with all its spans
1692
2517
  */
1693
- details() {
1694
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2518
+ getTrace(traceId) {
2519
+ return this.request(`/api/observability/traces/${traceId}`);
1695
2520
  }
1696
2521
  /**
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.
2522
+ * Retrieves paginated list of AI traces with optional filtering
2523
+ * @param params - Parameters for pagination and filtering
2524
+ * @returns Promise containing paginated traces and pagination info
1700
2525
  */
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;
2526
+ getTraces(params) {
2527
+ const { pagination, filters } = params;
2528
+ const { page, perPage, dateRange } = pagination || {};
2529
+ const { name, spanType, entityId, entityType } = filters || {};
2530
+ const searchParams = new URLSearchParams();
2531
+ if (page !== void 0) {
2532
+ searchParams.set("page", String(page));
1706
2533
  }
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
- });
2534
+ if (perPage !== void 0) {
2535
+ searchParams.set("perPage", String(perPage));
2536
+ }
2537
+ if (name) {
2538
+ searchParams.set("name", name);
2539
+ }
2540
+ if (spanType !== void 0) {
2541
+ searchParams.set("spanType", String(spanType));
2542
+ }
2543
+ if (entityId && entityType) {
2544
+ searchParams.set("entityId", entityId);
2545
+ searchParams.set("entityType", entityType);
2546
+ }
2547
+ if (dateRange) {
2548
+ const dateRangeStr = JSON.stringify({
2549
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2550
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2551
+ });
2552
+ searchParams.set("dateRange", dateRangeStr);
2553
+ }
2554
+ const queryString = searchParams.toString();
2555
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
1711
2556
  }
1712
2557
  };
1713
2558
 
@@ -1775,7 +2620,7 @@ var NetworkMemoryThread = class extends BaseResource {
1775
2620
  };
1776
2621
 
1777
2622
  // src/resources/vNextNetwork.ts
1778
- var RECORD_SEPARATOR3 = "";
2623
+ var RECORD_SEPARATOR4 = "";
1779
2624
  var VNextNetwork = class extends BaseResource {
1780
2625
  constructor(options, networkId) {
1781
2626
  super(options);
@@ -1827,7 +2672,7 @@ var VNextNetwork = class extends BaseResource {
1827
2672
  if (done && !value) continue;
1828
2673
  try {
1829
2674
  const decoded = value ? new TextDecoder().decode(value) : "";
1830
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2675
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
1831
2676
  buffer = chunks.pop() || "";
1832
2677
  for (const chunk of chunks) {
1833
2678
  if (chunk) {
@@ -1914,8 +2759,10 @@ var VNextNetwork = class extends BaseResource {
1914
2759
 
1915
2760
  // src/client.ts
1916
2761
  var MastraClient = class extends BaseResource {
2762
+ observability;
1917
2763
  constructor(options) {
1918
2764
  super(options);
2765
+ this.observability = new Observability(options);
1919
2766
  }
1920
2767
  /**
1921
2768
  * Retrieves all available agents
@@ -1924,21 +2771,6 @@ var MastraClient = class extends BaseResource {
1924
2771
  getAgents() {
1925
2772
  return this.request("/api/agents");
1926
2773
  }
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
2774
  /**
1943
2775
  * Gets an agent instance by ID
1944
2776
  * @param agentId - ID of the agent to retrieve
@@ -2044,7 +2876,7 @@ var MastraClient = class extends BaseResource {
2044
2876
  * @returns Tool instance
2045
2877
  */
2046
2878
  getTool(toolId) {
2047
- return new Tool2(this.options, toolId);
2879
+ return new Tool(this.options, toolId);
2048
2880
  }
2049
2881
  /**
2050
2882
  * Retrieves all available legacy workflows
@@ -2076,6 +2908,20 @@ var MastraClient = class extends BaseResource {
2076
2908
  getWorkflow(workflowId) {
2077
2909
  return new Workflow(this.options, workflowId);
2078
2910
  }
2911
+ /**
2912
+ * Gets all available agent builder actions
2913
+ * @returns Promise containing map of action IDs to action details
2914
+ */
2915
+ getAgentBuilderActions() {
2916
+ return this.request("/api/agent-builder/");
2917
+ }
2918
+ /**
2919
+ * Gets an agent builder instance for executing agent-builder workflows
2920
+ * @returns AgentBuilder instance
2921
+ */
2922
+ getAgentBuilderAction(actionId) {
2923
+ return new AgentBuilder(this.options, actionId);
2924
+ }
2079
2925
  /**
2080
2926
  * Gets a vector instance by name
2081
2927
  * @param vectorName - Name of the vector to retrieve
@@ -2419,6 +3265,19 @@ var MastraClient = class extends BaseResource {
2419
3265
  body: params
2420
3266
  });
2421
3267
  }
3268
+ /**
3269
+ * Retrieves model providers with available keys
3270
+ * @returns Promise containing model providers with available keys
3271
+ */
3272
+ getModelProviders() {
3273
+ return this.request(`/api/model-providers`);
3274
+ }
3275
+ getAITrace(traceId) {
3276
+ return this.observability.getTrace(traceId);
3277
+ }
3278
+ getAITraces(params) {
3279
+ return this.observability.getTraces(params);
3280
+ }
2422
3281
  };
2423
3282
 
2424
3283
  export { MastraClient };