@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.cjs CHANGED
@@ -1,223 +1,41 @@
1
1
  'use strict';
2
2
 
3
- var client = require('@ag-ui/client');
4
- var rxjs = require('rxjs');
5
3
  var uiUtils = require('@ai-sdk/ui-utils');
6
- var zod = require('zod');
7
- var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
9
4
  var uuid = require('@lukeed/uuid');
10
5
  var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
7
+ var zod = require('zod');
8
+ var originalZodToJsonSchema = require('zod-to-json-schema');
11
9
 
12
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
11
 
14
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
15
13
 
16
- // src/adapters/agui.ts
17
- var AGUIAdapter = class extends client.AbstractAgent {
18
- agent;
19
- resourceId;
20
- constructor({ agent, agentId, resourceId, ...rest }) {
21
- super({
22
- agentId,
23
- ...rest
24
- });
25
- this.agent = agent;
26
- this.resourceId = resourceId;
27
- }
28
- run(input) {
29
- return new rxjs.Observable((subscriber) => {
30
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
31
- subscriber.next({
32
- type: client.EventType.RUN_STARTED,
33
- threadId: input.threadId,
34
- runId: input.runId
35
- });
36
- this.agent.stream({
37
- threadId: input.threadId,
38
- resourceId: this.resourceId ?? "",
39
- runId: input.runId,
40
- messages: convertedMessages,
41
- clientTools: input.tools.reduce(
42
- (acc, tool) => {
43
- acc[tool.name] = {
44
- id: tool.name,
45
- description: tool.description,
46
- inputSchema: tool.parameters
47
- };
48
- return acc;
49
- },
50
- {}
51
- )
52
- }).then((response) => {
53
- let currentMessageId = void 0;
54
- let isInTextMessage = false;
55
- return response.processDataStream({
56
- onTextPart: (text) => {
57
- if (currentMessageId === void 0) {
58
- currentMessageId = generateUUID();
59
- const message2 = {
60
- type: client.EventType.TEXT_MESSAGE_START,
61
- messageId: currentMessageId,
62
- role: "assistant"
63
- };
64
- subscriber.next(message2);
65
- isInTextMessage = true;
66
- }
67
- const message = {
68
- type: client.EventType.TEXT_MESSAGE_CONTENT,
69
- messageId: currentMessageId,
70
- delta: text
71
- };
72
- subscriber.next(message);
73
- },
74
- onFinishMessagePart: () => {
75
- if (currentMessageId !== void 0) {
76
- const message = {
77
- type: client.EventType.TEXT_MESSAGE_END,
78
- messageId: currentMessageId
79
- };
80
- subscriber.next(message);
81
- isInTextMessage = false;
82
- }
83
- subscriber.next({
84
- type: client.EventType.RUN_FINISHED,
85
- threadId: input.threadId,
86
- runId: input.runId
87
- });
88
- subscriber.complete();
89
- },
90
- onToolCallPart(streamPart) {
91
- const parentMessageId = currentMessageId || generateUUID();
92
- if (isInTextMessage) {
93
- const message = {
94
- type: client.EventType.TEXT_MESSAGE_END,
95
- messageId: parentMessageId
96
- };
97
- subscriber.next(message);
98
- isInTextMessage = false;
99
- }
100
- subscriber.next({
101
- type: client.EventType.TOOL_CALL_START,
102
- toolCallId: streamPart.toolCallId,
103
- toolCallName: streamPart.toolName,
104
- parentMessageId
105
- });
106
- subscriber.next({
107
- type: client.EventType.TOOL_CALL_ARGS,
108
- toolCallId: streamPart.toolCallId,
109
- delta: JSON.stringify(streamPart.args),
110
- parentMessageId
111
- });
112
- subscriber.next({
113
- type: client.EventType.TOOL_CALL_END,
114
- toolCallId: streamPart.toolCallId,
115
- parentMessageId
116
- });
117
- }
118
- });
119
- }).catch((error) => {
120
- console.error("error", error);
121
- subscriber.error(error);
122
- });
123
- return () => {
124
- };
125
- });
126
- }
127
- };
128
- function generateUUID() {
129
- if (typeof crypto !== "undefined") {
130
- if (typeof crypto.randomUUID === "function") {
131
- return crypto.randomUUID();
132
- }
133
- if (typeof crypto.getRandomValues === "function") {
134
- const buffer = new Uint8Array(16);
135
- crypto.getRandomValues(buffer);
136
- buffer[6] = buffer[6] & 15 | 64;
137
- buffer[8] = buffer[8] & 63 | 128;
138
- let hex = "";
139
- for (let i = 0; i < 16; i++) {
140
- hex += buffer[i].toString(16).padStart(2, "0");
141
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
142
- }
143
- return hex;
14
+ // src/resources/agent.ts
15
+ function parseClientRuntimeContext(runtimeContext$1) {
16
+ if (runtimeContext$1) {
17
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
18
+ return Object.fromEntries(runtimeContext$1.entries());
144
19
  }
20
+ return runtimeContext$1;
145
21
  }
146
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
147
- const r = Math.random() * 16 | 0;
148
- const v = c === "x" ? r : r & 3 | 8;
149
- return v.toString(16);
150
- });
22
+ return void 0;
151
23
  }
152
- function convertMessagesToMastraMessages(messages) {
153
- const result = [];
154
- const toolCallsWithResults = /* @__PURE__ */ new Set();
155
- for (const message of messages) {
156
- if (message.role === "tool" && message.toolCallId) {
157
- toolCallsWithResults.add(message.toolCallId);
158
- }
159
- }
160
- for (const message of messages) {
161
- if (message.role === "assistant") {
162
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
163
- for (const toolCall of message.toolCalls ?? []) {
164
- parts.push({
165
- type: "tool-call",
166
- toolCallId: toolCall.id,
167
- toolName: toolCall.function.name,
168
- args: JSON.parse(toolCall.function.arguments)
169
- });
170
- }
171
- result.push({
172
- role: "assistant",
173
- content: parts
174
- });
175
- if (message.toolCalls?.length) {
176
- for (const toolCall of message.toolCalls) {
177
- if (!toolCallsWithResults.has(toolCall.id)) {
178
- result.push({
179
- role: "tool",
180
- content: [
181
- {
182
- type: "tool-result",
183
- toolCallId: toolCall.id,
184
- toolName: toolCall.function.name,
185
- result: JSON.parse(toolCall.function.arguments)
186
- // This is still wrong but matches test expectations
187
- }
188
- ]
189
- });
190
- }
191
- }
192
- }
193
- } else if (message.role === "user") {
194
- result.push({
195
- role: "user",
196
- content: message.content || ""
197
- });
198
- } else if (message.role === "tool") {
199
- result.push({
200
- role: "tool",
201
- content: [
202
- {
203
- type: "tool-result",
204
- toolCallId: message.toolCallId || "unknown",
205
- toolName: "unknown",
206
- // toolName is not available in tool messages from CopilotKit
207
- result: message.content
208
- }
209
- ]
210
- });
211
- }
212
- }
213
- return result;
24
+ function isZodType(value) {
25
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
214
26
  }
215
27
  function zodToJsonSchema(zodSchema) {
216
- if (!(zodSchema instanceof zod.ZodSchema)) {
28
+ if (!isZodType(zodSchema)) {
217
29
  return zodSchema;
218
30
  }
219
- return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
31
+ if ("toJSONSchema" in zod.z) {
32
+ const fn = "toJSONSchema";
33
+ return zod.z[fn].call(zod.z, zodSchema);
34
+ }
35
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "relative" });
220
36
  }
37
+
38
+ // src/utils/process-client-tools.ts
221
39
  function processClientTools(clientTools) {
222
40
  if (!clientTools) {
223
41
  return void 0;
@@ -246,6 +64,42 @@ function processClientTools(clientTools) {
246
64
  );
247
65
  }
248
66
 
67
+ // src/utils/process-mastra-stream.ts
68
+ async function processMastraStream({
69
+ stream,
70
+ onChunk
71
+ }) {
72
+ const reader = stream.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ try {
76
+ while (true) {
77
+ const { done, value } = await reader.read();
78
+ if (done) break;
79
+ buffer += decoder.decode(value, { stream: true });
80
+ const lines = buffer.split("\n\n");
81
+ buffer = lines.pop() || "";
82
+ for (const line of lines) {
83
+ if (line.startsWith("data: ")) {
84
+ const data = line.slice(6);
85
+ if (data === "[DONE]") {
86
+ console.log("\u{1F3C1} Stream finished");
87
+ return;
88
+ }
89
+ try {
90
+ const json = JSON.parse(data);
91
+ await onChunk(json);
92
+ } catch (error) {
93
+ console.error("\u274C JSON parse error:", error, "Data:", data);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ } finally {
99
+ reader.releaseLock();
100
+ }
101
+ }
102
+
249
103
  // src/resources/base.ts
250
104
  var BaseResource = class {
251
105
  options;
@@ -260,7 +114,7 @@ var BaseResource = class {
260
114
  */
261
115
  async request(path, options = {}) {
262
116
  let lastError = null;
263
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
117
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
264
118
  let delay = backoffMs;
265
119
  for (let attempt = 0; attempt <= retries; attempt++) {
266
120
  try {
@@ -274,6 +128,7 @@ var BaseResource = class {
274
128
  // 'x-mastra-client-type': 'js',
275
129
  },
276
130
  signal: this.options.abortSignal,
131
+ credentials: options.credentials ?? credentials,
277
132
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
278
133
  });
279
134
  if (!response.ok) {
@@ -306,14 +161,64 @@ var BaseResource = class {
306
161
  throw lastError || new Error("Request failed");
307
162
  }
308
163
  };
309
- function parseClientRuntimeContext(runtimeContext$1) {
310
- if (runtimeContext$1) {
311
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
312
- return Object.fromEntries(runtimeContext$1.entries());
164
+
165
+ // src/resources/agent.ts
166
+ async function executeToolCallAndRespond({
167
+ response,
168
+ params,
169
+ runId,
170
+ resourceId,
171
+ threadId,
172
+ runtimeContext,
173
+ respondFn
174
+ }) {
175
+ if (response.finishReason === "tool-calls") {
176
+ const toolCalls = response.toolCalls;
177
+ if (!toolCalls || !Array.isArray(toolCalls)) {
178
+ return response;
179
+ }
180
+ for (const toolCall of toolCalls) {
181
+ const clientTool = params.clientTools?.[toolCall.toolName];
182
+ if (clientTool && clientTool.execute) {
183
+ const result = await clientTool.execute(
184
+ {
185
+ context: toolCall?.args,
186
+ runId,
187
+ resourceId,
188
+ threadId,
189
+ runtimeContext,
190
+ tracingContext: { currentSpan: void 0 }
191
+ },
192
+ {
193
+ messages: response.messages,
194
+ toolCallId: toolCall?.toolCallId
195
+ }
196
+ );
197
+ const updatedMessages = [
198
+ {
199
+ role: "user",
200
+ content: params.messages
201
+ },
202
+ ...response.response.messages,
203
+ {
204
+ role: "tool",
205
+ content: [
206
+ {
207
+ type: "tool-result",
208
+ toolCallId: toolCall.toolCallId,
209
+ toolName: toolCall.toolName,
210
+ result
211
+ }
212
+ ]
213
+ }
214
+ ];
215
+ return respondFn({
216
+ ...params,
217
+ messages: updatedMessages
218
+ });
219
+ }
313
220
  }
314
- return runtimeContext$1;
315
221
  }
316
- return void 0;
317
222
  }
318
223
  var AgentVoice = class extends BaseResource {
319
224
  constructor(options, agentId) {
@@ -384,6 +289,12 @@ var Agent = class extends BaseResource {
384
289
  return this.request(`/api/agents/${this.agentId}`);
385
290
  }
386
291
  async generate(params) {
292
+ console.warn(
293
+ "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."
294
+ );
295
+ return this.generateLegacy(params);
296
+ }
297
+ async generateLegacy(params) {
387
298
  const processedParams = {
388
299
  ...params,
389
300
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -393,7 +304,7 @@ var Agent = class extends BaseResource {
393
304
  };
394
305
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
395
306
  const response = await this.request(
396
- `/api/agents/${this.agentId}/generate`,
307
+ `/api/agents/${this.agentId}/generate-legacy`,
397
308
  {
398
309
  method: "POST",
399
310
  body: processedParams
@@ -408,7 +319,14 @@ var Agent = class extends BaseResource {
408
319
  const clientTool = params.clientTools?.[toolCall.toolName];
409
320
  if (clientTool && clientTool.execute) {
410
321
  const result = await clientTool.execute(
411
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
322
+ {
323
+ context: toolCall?.args,
324
+ runId,
325
+ resourceId,
326
+ threadId,
327
+ runtimeContext,
328
+ tracingContext: { currentSpan: void 0 }
329
+ },
412
330
  {
413
331
  messages: response.messages,
414
332
  toolCallId: toolCall?.toolCallId
@@ -441,6 +359,38 @@ var Agent = class extends BaseResource {
441
359
  }
442
360
  return response;
443
361
  }
362
+ async generateVNext(params) {
363
+ const processedParams = {
364
+ ...params,
365
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
366
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
367
+ clientTools: processClientTools(params.clientTools),
368
+ structuredOutput: params.structuredOutput ? {
369
+ ...params.structuredOutput,
370
+ schema: zodToJsonSchema(params.structuredOutput.schema)
371
+ } : void 0
372
+ };
373
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
374
+ const response = await this.request(
375
+ `/api/agents/${this.agentId}/generate/vnext`,
376
+ {
377
+ method: "POST",
378
+ body: processedParams
379
+ }
380
+ );
381
+ if (response.finishReason === "tool-calls") {
382
+ return executeToolCallAndRespond({
383
+ response,
384
+ params,
385
+ runId,
386
+ resourceId,
387
+ threadId,
388
+ runtimeContext,
389
+ respondFn: this.generateVNext.bind(this)
390
+ });
391
+ }
392
+ return response;
393
+ }
444
394
  async processChatResponse({
445
395
  stream,
446
396
  update,
@@ -709,6 +659,17 @@ var Agent = class extends BaseResource {
709
659
  * @returns Promise containing the enhanced Response object with processDataStream method
710
660
  */
711
661
  async stream(params) {
662
+ console.warn(
663
+ "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."
664
+ );
665
+ return this.streamLegacy(params);
666
+ }
667
+ /**
668
+ * Streams a response from the agent
669
+ * @param params - Stream parameters including prompt
670
+ * @returns Promise containing the enhanced Response object with processDataStream method
671
+ */
672
+ async streamLegacy(params) {
712
673
  const processedParams = {
713
674
  ...params,
714
675
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -731,11 +692,261 @@ var Agent = class extends BaseResource {
731
692
  };
732
693
  return streamResponse;
733
694
  }
734
- /**
735
- * Processes the stream response and handles tool calls
736
- */
737
- async processStreamResponse(processedParams, writable) {
738
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
695
+ async processChatResponse_vNext({
696
+ stream,
697
+ update,
698
+ onToolCall,
699
+ onFinish,
700
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
701
+ lastMessage
702
+ }) {
703
+ const replaceLastMessage = lastMessage?.role === "assistant";
704
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
705
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
706
+ return Math.max(max, toolInvocation.step ?? 0);
707
+ }, 0) ?? 0) : 0;
708
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
709
+ id: uuid.v4(),
710
+ createdAt: getCurrentDate(),
711
+ role: "assistant",
712
+ content: "",
713
+ parts: []
714
+ };
715
+ let currentTextPart = void 0;
716
+ let currentReasoningPart = void 0;
717
+ let currentReasoningTextDetail = void 0;
718
+ function updateToolInvocationPart(toolCallId, invocation) {
719
+ const part = message.parts.find(
720
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
721
+ );
722
+ if (part != null) {
723
+ part.toolInvocation = invocation;
724
+ } else {
725
+ message.parts.push({
726
+ type: "tool-invocation",
727
+ toolInvocation: invocation
728
+ });
729
+ }
730
+ }
731
+ const data = [];
732
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
733
+ const partialToolCalls = {};
734
+ let usage = {
735
+ completionTokens: NaN,
736
+ promptTokens: NaN,
737
+ totalTokens: NaN
738
+ };
739
+ let finishReason = "unknown";
740
+ function execUpdate() {
741
+ const copiedData = [...data];
742
+ if (messageAnnotations?.length) {
743
+ message.annotations = messageAnnotations;
744
+ }
745
+ const copiedMessage = {
746
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
747
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
748
+ ...structuredClone(message),
749
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
750
+ // hashing approach by default to detect changes, but it only works for shallow
751
+ // changes. This is why we need to add a revision id to ensure that the message
752
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
753
+ // forwarded to rendering):
754
+ revisionId: uuid.v4()
755
+ };
756
+ update({
757
+ message: copiedMessage,
758
+ data: copiedData,
759
+ replaceLastMessage
760
+ });
761
+ }
762
+ await processMastraStream({
763
+ stream,
764
+ // TODO: casting as any here because the stream types were all typed as any before in core.
765
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
766
+ onChunk: async (chunk) => {
767
+ switch (chunk.type) {
768
+ case "step-start": {
769
+ if (!replaceLastMessage) {
770
+ message.id = chunk.payload.messageId;
771
+ }
772
+ message.parts.push({ type: "step-start" });
773
+ execUpdate();
774
+ break;
775
+ }
776
+ case "text-delta": {
777
+ if (currentTextPart == null) {
778
+ currentTextPart = {
779
+ type: "text",
780
+ text: chunk.payload.text
781
+ };
782
+ message.parts.push(currentTextPart);
783
+ } else {
784
+ currentTextPart.text += chunk.payload.text;
785
+ }
786
+ message.content += chunk.payload.text;
787
+ execUpdate();
788
+ break;
789
+ }
790
+ case "reasoning-delta": {
791
+ if (currentReasoningTextDetail == null) {
792
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
793
+ if (currentReasoningPart != null) {
794
+ currentReasoningPart.details.push(currentReasoningTextDetail);
795
+ }
796
+ } else {
797
+ currentReasoningTextDetail.text += chunk.payload.text;
798
+ }
799
+ if (currentReasoningPart == null) {
800
+ currentReasoningPart = {
801
+ type: "reasoning",
802
+ reasoning: chunk.payload.text,
803
+ details: [currentReasoningTextDetail]
804
+ };
805
+ message.parts.push(currentReasoningPart);
806
+ } else {
807
+ currentReasoningPart.reasoning += chunk.payload.text;
808
+ }
809
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
810
+ execUpdate();
811
+ break;
812
+ }
813
+ case "file": {
814
+ message.parts.push({
815
+ type: "file",
816
+ mimeType: chunk.payload.mimeType,
817
+ data: chunk.payload.data
818
+ });
819
+ execUpdate();
820
+ break;
821
+ }
822
+ case "source": {
823
+ message.parts.push({
824
+ type: "source",
825
+ source: chunk.payload.source
826
+ });
827
+ execUpdate();
828
+ break;
829
+ }
830
+ case "tool-call": {
831
+ const invocation = {
832
+ state: "call",
833
+ step,
834
+ ...chunk.payload
835
+ };
836
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
837
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
838
+ } else {
839
+ if (message.toolInvocations == null) {
840
+ message.toolInvocations = [];
841
+ }
842
+ message.toolInvocations.push(invocation);
843
+ }
844
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
845
+ execUpdate();
846
+ if (onToolCall) {
847
+ const result = await onToolCall({ toolCall: chunk.payload });
848
+ if (result != null) {
849
+ const invocation2 = {
850
+ state: "result",
851
+ step,
852
+ ...chunk.payload,
853
+ result
854
+ };
855
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
856
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
857
+ execUpdate();
858
+ }
859
+ }
860
+ }
861
+ case "tool-call-input-streaming-start": {
862
+ if (message.toolInvocations == null) {
863
+ message.toolInvocations = [];
864
+ }
865
+ partialToolCalls[chunk.payload.toolCallId] = {
866
+ text: "",
867
+ step,
868
+ toolName: chunk.payload.toolName,
869
+ index: message.toolInvocations.length
870
+ };
871
+ const invocation = {
872
+ state: "partial-call",
873
+ step,
874
+ toolCallId: chunk.payload.toolCallId,
875
+ toolName: chunk.payload.toolName,
876
+ args: chunk.payload.args
877
+ };
878
+ message.toolInvocations.push(invocation);
879
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
880
+ execUpdate();
881
+ break;
882
+ }
883
+ case "tool-call-delta": {
884
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
885
+ partialToolCall.text += chunk.payload.argsTextDelta;
886
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
887
+ const invocation = {
888
+ state: "partial-call",
889
+ step: partialToolCall.step,
890
+ toolCallId: chunk.payload.toolCallId,
891
+ toolName: partialToolCall.toolName,
892
+ args: partialArgs
893
+ };
894
+ message.toolInvocations[partialToolCall.index] = invocation;
895
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
896
+ execUpdate();
897
+ break;
898
+ }
899
+ case "tool-result": {
900
+ const toolInvocations = message.toolInvocations;
901
+ if (toolInvocations == null) {
902
+ throw new Error("tool_result must be preceded by a tool_call");
903
+ }
904
+ const toolInvocationIndex = toolInvocations.findIndex(
905
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
906
+ );
907
+ if (toolInvocationIndex === -1) {
908
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
909
+ }
910
+ const invocation = {
911
+ ...toolInvocations[toolInvocationIndex],
912
+ state: "result",
913
+ ...chunk.payload
914
+ };
915
+ toolInvocations[toolInvocationIndex] = invocation;
916
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
917
+ execUpdate();
918
+ break;
919
+ }
920
+ case "error": {
921
+ throw new Error(chunk.payload.error);
922
+ }
923
+ case "data": {
924
+ data.push(...chunk.payload.data);
925
+ execUpdate();
926
+ break;
927
+ }
928
+ case "step-finish": {
929
+ step += 1;
930
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
931
+ currentReasoningPart = void 0;
932
+ currentReasoningTextDetail = void 0;
933
+ execUpdate();
934
+ break;
935
+ }
936
+ case "finish": {
937
+ finishReason = chunk.payload.stepResult.reason;
938
+ if (chunk.payload.usage != null) {
939
+ usage = chunk.payload.usage;
940
+ }
941
+ break;
942
+ }
943
+ }
944
+ }
945
+ });
946
+ onFinish?.({ message, finishReason, usage });
947
+ }
948
+ async processStreamResponse_vNext(processedParams, writable) {
949
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
739
950
  method: "POST",
740
951
  body: processedParams,
741
952
  stream: true
@@ -747,12 +958,31 @@ var Agent = class extends BaseResource {
747
958
  let toolCalls = [];
748
959
  let messages = [];
749
960
  const [streamForWritable, streamForProcessing] = response.body.tee();
750
- streamForWritable.pipeTo(writable, {
751
- preventClose: true
752
- }).catch((error) => {
961
+ streamForWritable.pipeTo(
962
+ new WritableStream({
963
+ async write(chunk) {
964
+ try {
965
+ const text = new TextDecoder().decode(chunk);
966
+ if (text.includes("[DONE]")) {
967
+ return;
968
+ }
969
+ } catch {
970
+ }
971
+ const writer = writable.getWriter();
972
+ try {
973
+ await writer.write(chunk);
974
+ } finally {
975
+ writer.releaseLock();
976
+ }
977
+ }
978
+ }),
979
+ {
980
+ preventClose: true
981
+ }
982
+ ).catch((error) => {
753
983
  console.error("Error piping to writable stream:", error);
754
984
  });
755
- this.processChatResponse({
985
+ this.processChatResponse_vNext({
756
986
  stream: streamForProcessing,
757
987
  update: ({ message }) => {
758
988
  const existingIndex = messages.findIndex((m) => m.id === message.id);
@@ -777,14 +1007,17 @@ var Agent = class extends BaseResource {
777
1007
  runId: processedParams.runId,
778
1008
  resourceId: processedParams.resourceId,
779
1009
  threadId: processedParams.threadId,
780
- runtimeContext: processedParams.runtimeContext
1010
+ runtimeContext: processedParams.runtimeContext,
1011
+ // TODO: Pass proper tracing context when client-js supports tracing
1012
+ tracingContext: { currentSpan: void 0 }
781
1013
  },
782
1014
  {
783
1015
  messages: response.messages,
784
1016
  toolCallId: toolCall2?.toolCallId
785
1017
  }
786
1018
  );
787
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1019
+ const lastMessageRaw = messages[messages.length - 1];
1020
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
788
1021
  const toolInvocationPart = lastMessage?.parts?.find(
789
1022
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
790
1023
  );
@@ -802,11 +1035,141 @@ var Agent = class extends BaseResource {
802
1035
  toolInvocation.state = "result";
803
1036
  toolInvocation.result = result;
804
1037
  }
805
- const writer = writable.getWriter();
806
- try {
807
- await writer.write(
808
- new TextEncoder().encode(
809
- "a:" + JSON.stringify({
1038
+ const originalMessages = processedParams.messages;
1039
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
1040
+ const updatedMessages = lastMessage != null ? [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messageArray, ...messages];
1041
+ this.processStreamResponse_vNext(
1042
+ {
1043
+ ...processedParams,
1044
+ messages: updatedMessages
1045
+ },
1046
+ writable
1047
+ ).catch((error) => {
1048
+ console.error("Error processing stream response:", error);
1049
+ });
1050
+ }
1051
+ }
1052
+ } else {
1053
+ setTimeout(() => {
1054
+ writable.close();
1055
+ }, 0);
1056
+ }
1057
+ },
1058
+ lastMessage: void 0
1059
+ }).catch((error) => {
1060
+ console.error("Error processing stream response:", error);
1061
+ });
1062
+ } catch (error) {
1063
+ console.error("Error processing stream response:", error);
1064
+ }
1065
+ return response;
1066
+ }
1067
+ async streamVNext(params) {
1068
+ const processedParams = {
1069
+ ...params,
1070
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1071
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1072
+ clientTools: processClientTools(params.clientTools),
1073
+ structuredOutput: params.structuredOutput ? {
1074
+ ...params.structuredOutput,
1075
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1076
+ } : void 0
1077
+ };
1078
+ const { readable, writable } = new TransformStream();
1079
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1080
+ const streamResponse = new Response(readable, {
1081
+ status: response.status,
1082
+ statusText: response.statusText,
1083
+ headers: response.headers
1084
+ });
1085
+ streamResponse.processDataStream = async ({
1086
+ onChunk
1087
+ }) => {
1088
+ await processMastraStream({
1089
+ stream: streamResponse.body,
1090
+ onChunk
1091
+ });
1092
+ };
1093
+ return streamResponse;
1094
+ }
1095
+ /**
1096
+ * Processes the stream response and handles tool calls
1097
+ */
1098
+ async processStreamResponse(processedParams, writable) {
1099
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1100
+ method: "POST",
1101
+ body: processedParams,
1102
+ stream: true
1103
+ });
1104
+ if (!response.body) {
1105
+ throw new Error("No response body");
1106
+ }
1107
+ try {
1108
+ let toolCalls = [];
1109
+ let messages = [];
1110
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1111
+ streamForWritable.pipeTo(writable, {
1112
+ preventClose: true
1113
+ }).catch((error) => {
1114
+ console.error("Error piping to writable stream:", error);
1115
+ });
1116
+ this.processChatResponse({
1117
+ stream: streamForProcessing,
1118
+ update: ({ message }) => {
1119
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1120
+ if (existingIndex !== -1) {
1121
+ messages[existingIndex] = message;
1122
+ } else {
1123
+ messages.push(message);
1124
+ }
1125
+ },
1126
+ onFinish: async ({ finishReason, message }) => {
1127
+ if (finishReason === "tool-calls") {
1128
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1129
+ if (toolCall) {
1130
+ toolCalls.push(toolCall);
1131
+ }
1132
+ for (const toolCall2 of toolCalls) {
1133
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1134
+ if (clientTool && clientTool.execute) {
1135
+ const result = await clientTool.execute(
1136
+ {
1137
+ context: toolCall2?.args,
1138
+ runId: processedParams.runId,
1139
+ resourceId: processedParams.resourceId,
1140
+ threadId: processedParams.threadId,
1141
+ runtimeContext: processedParams.runtimeContext,
1142
+ // TODO: Pass proper tracing context when client-js supports tracing
1143
+ tracingContext: { currentSpan: void 0 }
1144
+ },
1145
+ {
1146
+ messages: response.messages,
1147
+ toolCallId: toolCall2?.toolCallId
1148
+ }
1149
+ );
1150
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1151
+ const toolInvocationPart = lastMessage?.parts?.find(
1152
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1153
+ );
1154
+ if (toolInvocationPart) {
1155
+ toolInvocationPart.toolInvocation = {
1156
+ ...toolInvocationPart.toolInvocation,
1157
+ state: "result",
1158
+ result
1159
+ };
1160
+ }
1161
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1162
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1163
+ );
1164
+ if (toolInvocation) {
1165
+ toolInvocation.state = "result";
1166
+ toolInvocation.result = result;
1167
+ }
1168
+ const writer = writable.getWriter();
1169
+ try {
1170
+ await writer.write(
1171
+ new TextEncoder().encode(
1172
+ "a:" + JSON.stringify({
810
1173
  toolCallId: toolCall2.toolCallId,
811
1174
  result
812
1175
  }) + "\n"
@@ -881,6 +1244,17 @@ var Agent = class extends BaseResource {
881
1244
  liveEvals() {
882
1245
  return this.request(`/api/agents/${this.agentId}/evals/live`);
883
1246
  }
1247
+ /**
1248
+ * Updates the model for the agent
1249
+ * @param params - Parameters for updating the model
1250
+ * @returns Promise containing the updated model
1251
+ */
1252
+ updateModel(params) {
1253
+ return this.request(`/api/agents/${this.agentId}/model`, {
1254
+ method: "POST",
1255
+ body: params
1256
+ });
1257
+ }
884
1258
  };
885
1259
  var Network = class extends BaseResource {
886
1260
  constructor(options, networkId) {
@@ -1265,7 +1639,7 @@ var LegacyWorkflow = class extends BaseResource {
1265
1639
  };
1266
1640
 
1267
1641
  // src/resources/tool.ts
1268
- var Tool2 = class extends BaseResource {
1642
+ var Tool = class extends BaseResource {
1269
1643
  constructor(options, toolId) {
1270
1644
  super(options);
1271
1645
  this.toolId = toolId;
@@ -1489,32 +1863,472 @@ var Workflow = class extends BaseResource {
1489
1863
  searchParams.set("runId", params.runId);
1490
1864
  }
1491
1865
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1492
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1866
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1867
+ method: "POST",
1868
+ body: { inputData: params.inputData, runtimeContext }
1869
+ });
1870
+ }
1871
+ /**
1872
+ * Starts a workflow run and returns a stream
1873
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1874
+ * @returns Promise containing the workflow execution results
1875
+ */
1876
+ async stream(params) {
1877
+ const searchParams = new URLSearchParams();
1878
+ if (!!params?.runId) {
1879
+ searchParams.set("runId", params.runId);
1880
+ }
1881
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1882
+ const response = await this.request(
1883
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1884
+ {
1885
+ method: "POST",
1886
+ body: { inputData: params.inputData, runtimeContext },
1887
+ stream: true
1888
+ }
1889
+ );
1890
+ if (!response.ok) {
1891
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1892
+ }
1893
+ if (!response.body) {
1894
+ throw new Error("Response body is null");
1895
+ }
1896
+ let failedChunk = void 0;
1897
+ const transformStream = new TransformStream({
1898
+ start() {
1899
+ },
1900
+ async transform(chunk, controller) {
1901
+ try {
1902
+ const decoded = new TextDecoder().decode(chunk);
1903
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1904
+ for (const chunk2 of chunks) {
1905
+ if (chunk2) {
1906
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1907
+ try {
1908
+ const parsedChunk = JSON.parse(newChunk);
1909
+ controller.enqueue(parsedChunk);
1910
+ failedChunk = void 0;
1911
+ } catch {
1912
+ failedChunk = newChunk;
1913
+ }
1914
+ }
1915
+ }
1916
+ } catch {
1917
+ }
1918
+ }
1919
+ });
1920
+ return response.body.pipeThrough(transformStream);
1921
+ }
1922
+ /**
1923
+ * Starts a workflow run and returns a stream
1924
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1925
+ * @returns Promise containing the workflow execution results
1926
+ */
1927
+ async streamVNext(params) {
1928
+ const searchParams = new URLSearchParams();
1929
+ if (!!params?.runId) {
1930
+ searchParams.set("runId", params.runId);
1931
+ }
1932
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1933
+ const response = await this.request(
1934
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1935
+ {
1936
+ method: "POST",
1937
+ body: { inputData: params.inputData, runtimeContext },
1938
+ stream: true
1939
+ }
1940
+ );
1941
+ if (!response.ok) {
1942
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1943
+ }
1944
+ if (!response.body) {
1945
+ throw new Error("Response body is null");
1946
+ }
1947
+ let failedChunk = void 0;
1948
+ const transformStream = new TransformStream({
1949
+ start() {
1950
+ },
1951
+ async transform(chunk, controller) {
1952
+ try {
1953
+ const decoded = new TextDecoder().decode(chunk);
1954
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1955
+ for (const chunk2 of chunks) {
1956
+ if (chunk2) {
1957
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1958
+ try {
1959
+ const parsedChunk = JSON.parse(newChunk);
1960
+ controller.enqueue(parsedChunk);
1961
+ failedChunk = void 0;
1962
+ } catch {
1963
+ failedChunk = newChunk;
1964
+ }
1965
+ }
1966
+ }
1967
+ } catch {
1968
+ }
1969
+ }
1970
+ });
1971
+ return response.body.pipeThrough(transformStream);
1972
+ }
1973
+ /**
1974
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1975
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1976
+ * @returns Promise containing the workflow resume results
1977
+ */
1978
+ resumeAsync(params) {
1979
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1980
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1981
+ method: "POST",
1982
+ body: {
1983
+ step: params.step,
1984
+ resumeData: params.resumeData,
1985
+ runtimeContext
1986
+ }
1987
+ });
1988
+ }
1989
+ /**
1990
+ * Watches workflow transitions in real-time
1991
+ * @param runId - Optional run ID to filter the watch stream
1992
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1993
+ */
1994
+ async watch({ runId }, onRecord) {
1995
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1996
+ stream: true
1997
+ });
1998
+ if (!response.ok) {
1999
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
2000
+ }
2001
+ if (!response.body) {
2002
+ throw new Error("Response body is null");
2003
+ }
2004
+ for await (const record of this.streamProcessor(response.body)) {
2005
+ if (typeof record === "string") {
2006
+ onRecord(JSON.parse(record));
2007
+ } else {
2008
+ onRecord(record);
2009
+ }
2010
+ }
2011
+ }
2012
+ /**
2013
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
2014
+ * serializing each as JSON and separating them with the record separator (\x1E).
2015
+ *
2016
+ * @param records - An iterable or async iterable of objects to stream
2017
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2018
+ */
2019
+ static createRecordStream(records) {
2020
+ const encoder = new TextEncoder();
2021
+ return new ReadableStream({
2022
+ async start(controller) {
2023
+ try {
2024
+ for await (const record of records) {
2025
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2026
+ controller.enqueue(encoder.encode(json));
2027
+ }
2028
+ controller.close();
2029
+ } catch (err) {
2030
+ controller.error(err);
2031
+ }
2032
+ }
2033
+ });
2034
+ }
2035
+ };
2036
+
2037
+ // src/resources/a2a.ts
2038
+ var A2A = class extends BaseResource {
2039
+ constructor(options, agentId) {
2040
+ super(options);
2041
+ this.agentId = agentId;
2042
+ }
2043
+ /**
2044
+ * Get the agent card with metadata about the agent
2045
+ * @returns Promise containing the agent card information
2046
+ */
2047
+ async getCard() {
2048
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
2049
+ }
2050
+ /**
2051
+ * Send a message to the agent and gets a message or task response
2052
+ * @param params - Parameters for the task
2053
+ * @returns Promise containing the response
2054
+ */
2055
+ async sendMessage(params) {
2056
+ const response = await this.request(`/a2a/${this.agentId}`, {
2057
+ method: "POST",
2058
+ body: {
2059
+ method: "message/send",
2060
+ params
2061
+ }
2062
+ });
2063
+ return response;
2064
+ }
2065
+ /**
2066
+ * Sends a message to an agent to initiate/continue a task and subscribes
2067
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2068
+ * @param params - Parameters for the task
2069
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2070
+ */
2071
+ async sendStreamingMessage(params) {
2072
+ const response = await this.request(`/a2a/${this.agentId}`, {
2073
+ method: "POST",
2074
+ body: {
2075
+ method: "message/stream",
2076
+ params
2077
+ }
2078
+ });
2079
+ return response;
2080
+ }
2081
+ /**
2082
+ * Get the status and result of a task
2083
+ * @param params - Parameters for querying the task
2084
+ * @returns Promise containing the task response
2085
+ */
2086
+ async getTask(params) {
2087
+ const response = await this.request(`/a2a/${this.agentId}`, {
2088
+ method: "POST",
2089
+ body: {
2090
+ method: "tasks/get",
2091
+ params
2092
+ }
2093
+ });
2094
+ return response;
2095
+ }
2096
+ /**
2097
+ * Cancel a running task
2098
+ * @param params - Parameters identifying the task to cancel
2099
+ * @returns Promise containing the task response
2100
+ */
2101
+ async cancelTask(params) {
2102
+ return this.request(`/a2a/${this.agentId}`, {
2103
+ method: "POST",
2104
+ body: {
2105
+ method: "tasks/cancel",
2106
+ params
2107
+ }
2108
+ });
2109
+ }
2110
+ };
2111
+
2112
+ // src/resources/mcp-tool.ts
2113
+ var MCPTool = class extends BaseResource {
2114
+ serverId;
2115
+ toolId;
2116
+ constructor(options, serverId, toolId) {
2117
+ super(options);
2118
+ this.serverId = serverId;
2119
+ this.toolId = toolId;
2120
+ }
2121
+ /**
2122
+ * Retrieves details about this specific tool from the MCP server.
2123
+ * @returns Promise containing the tool's information (name, description, schema).
2124
+ */
2125
+ details() {
2126
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2127
+ }
2128
+ /**
2129
+ * Executes this specific tool on the MCP server.
2130
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2131
+ * @returns Promise containing the result of the tool execution.
2132
+ */
2133
+ execute(params) {
2134
+ const body = {};
2135
+ if (params.data !== void 0) body.data = params.data;
2136
+ if (params.runtimeContext !== void 0) {
2137
+ body.runtimeContext = params.runtimeContext;
2138
+ }
2139
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2140
+ method: "POST",
2141
+ body: Object.keys(body).length > 0 ? body : void 0
2142
+ });
2143
+ }
2144
+ };
2145
+
2146
+ // src/resources/agent-builder.ts
2147
+ var RECORD_SEPARATOR3 = "";
2148
+ var AgentBuilder = class extends BaseResource {
2149
+ constructor(options, actionId) {
2150
+ super(options);
2151
+ this.actionId = actionId;
2152
+ }
2153
+ // Helper function to transform workflow result to action result
2154
+ transformWorkflowResult(result) {
2155
+ if (result.status === "success") {
2156
+ return {
2157
+ success: result.result.success || false,
2158
+ applied: result.result.applied || false,
2159
+ branchName: result.result.branchName,
2160
+ message: result.result.message || "Agent builder action completed",
2161
+ validationResults: result.result.validationResults,
2162
+ error: result.result.error,
2163
+ errors: result.result.errors,
2164
+ stepResults: result.result.stepResults
2165
+ };
2166
+ } else if (result.status === "failed") {
2167
+ return {
2168
+ success: false,
2169
+ applied: false,
2170
+ message: `Agent builder action failed: ${result.error.message}`,
2171
+ error: result.error.message
2172
+ };
2173
+ } else {
2174
+ return {
2175
+ success: false,
2176
+ applied: false,
2177
+ message: "Agent builder action was suspended",
2178
+ error: "Workflow suspended - manual intervention required"
2179
+ };
2180
+ }
2181
+ }
2182
+ /**
2183
+ * Creates a new agent builder action run and returns the runId.
2184
+ * This calls `/api/agent-builder/:actionId/create-run`.
2185
+ */
2186
+ async createRun(params) {
2187
+ const searchParams = new URLSearchParams();
2188
+ if (!!params?.runId) {
2189
+ searchParams.set("runId", params.runId);
2190
+ }
2191
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2192
+ return this.request(url, {
2193
+ method: "POST"
2194
+ });
2195
+ }
2196
+ /**
2197
+ * Creates a new workflow run (alias for createRun)
2198
+ * @param params - Optional object containing the optional runId
2199
+ * @returns Promise containing the runId of the created run
2200
+ */
2201
+ createRunAsync(params) {
2202
+ return this.createRun(params);
2203
+ }
2204
+ /**
2205
+ * Starts agent builder action asynchronously and waits for completion.
2206
+ * This calls `/api/agent-builder/:actionId/start-async`.
2207
+ */
2208
+ async startAsync(params, runId) {
2209
+ const searchParams = new URLSearchParams();
2210
+ if (runId) {
2211
+ searchParams.set("runId", runId);
2212
+ }
2213
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2214
+ const { runtimeContext: _, ...actionParams } = params;
2215
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2216
+ const result = await this.request(url, {
2217
+ method: "POST",
2218
+ body: { ...actionParams, runtimeContext }
2219
+ });
2220
+ return this.transformWorkflowResult(result);
2221
+ }
2222
+ /**
2223
+ * Starts an existing agent builder action run.
2224
+ * This calls `/api/agent-builder/:actionId/start`.
2225
+ */
2226
+ async startActionRun(params, runId) {
2227
+ const searchParams = new URLSearchParams();
2228
+ searchParams.set("runId", runId);
2229
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2230
+ const { runtimeContext: _, ...actionParams } = params;
2231
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2232
+ return this.request(url, {
2233
+ method: "POST",
2234
+ body: { ...actionParams, runtimeContext }
2235
+ });
2236
+ }
2237
+ /**
2238
+ * Resumes a suspended agent builder action step.
2239
+ * This calls `/api/agent-builder/:actionId/resume`.
2240
+ */
2241
+ async resume(params, runId) {
2242
+ const searchParams = new URLSearchParams();
2243
+ searchParams.set("runId", runId);
2244
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2245
+ const { runtimeContext: _, ...resumeParams } = params;
2246
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2247
+ return this.request(url, {
2248
+ method: "POST",
2249
+ body: { ...resumeParams, runtimeContext }
2250
+ });
2251
+ }
2252
+ /**
2253
+ * Resumes a suspended agent builder action step asynchronously.
2254
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2255
+ */
2256
+ async resumeAsync(params, runId) {
2257
+ const searchParams = new URLSearchParams();
2258
+ searchParams.set("runId", runId);
2259
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2260
+ const { runtimeContext: _, ...resumeParams } = params;
2261
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2262
+ const result = await this.request(url, {
1493
2263
  method: "POST",
1494
- body: { inputData: params.inputData, runtimeContext }
2264
+ body: { ...resumeParams, runtimeContext }
1495
2265
  });
2266
+ return this.transformWorkflowResult(result);
1496
2267
  }
1497
2268
  /**
1498
- * Starts a workflow run and returns a stream
1499
- * @param params - Object containing the optional runId, inputData and runtimeContext
1500
- * @returns Promise containing the workflow execution results
2269
+ * Creates an async generator that processes a readable stream and yields action records
2270
+ * separated by the Record Separator character (\x1E)
2271
+ *
2272
+ * @param stream - The readable stream to process
2273
+ * @returns An async generator that yields parsed records
1501
2274
  */
1502
- async stream(params) {
2275
+ async *streamProcessor(stream) {
2276
+ const reader = stream.getReader();
2277
+ let doneReading = false;
2278
+ let buffer = "";
2279
+ try {
2280
+ while (!doneReading) {
2281
+ const { done, value } = await reader.read();
2282
+ doneReading = done;
2283
+ if (done && !value) continue;
2284
+ try {
2285
+ const decoded = value ? new TextDecoder().decode(value) : "";
2286
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2287
+ buffer = chunks.pop() || "";
2288
+ for (const chunk of chunks) {
2289
+ if (chunk) {
2290
+ if (typeof chunk === "string") {
2291
+ try {
2292
+ const parsedChunk = JSON.parse(chunk);
2293
+ yield parsedChunk;
2294
+ } catch {
2295
+ }
2296
+ }
2297
+ }
2298
+ }
2299
+ } catch {
2300
+ }
2301
+ }
2302
+ if (buffer) {
2303
+ try {
2304
+ yield JSON.parse(buffer);
2305
+ } catch {
2306
+ }
2307
+ }
2308
+ } finally {
2309
+ reader.cancel().catch(() => {
2310
+ });
2311
+ }
2312
+ }
2313
+ /**
2314
+ * Streams agent builder action progress in real-time.
2315
+ * This calls `/api/agent-builder/:actionId/stream`.
2316
+ */
2317
+ async stream(params, runId) {
1503
2318
  const searchParams = new URLSearchParams();
1504
- if (!!params?.runId) {
1505
- searchParams.set("runId", params.runId);
2319
+ if (runId) {
2320
+ searchParams.set("runId", runId);
1506
2321
  }
1507
2322
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1508
- const response = await this.request(
1509
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1510
- {
1511
- method: "POST",
1512
- body: { inputData: params.inputData, runtimeContext },
1513
- stream: true
1514
- }
1515
- );
2323
+ const { runtimeContext: _, ...actionParams } = params;
2324
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2325
+ const response = await this.request(url, {
2326
+ method: "POST",
2327
+ body: { ...actionParams, runtimeContext },
2328
+ stream: true
2329
+ });
1516
2330
  if (!response.ok) {
1517
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2331
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
1518
2332
  }
1519
2333
  if (!response.body) {
1520
2334
  throw new Error("Response body is null");
@@ -1526,7 +2340,7 @@ var Workflow = class extends BaseResource {
1526
2340
  async transform(chunk, controller) {
1527
2341
  try {
1528
2342
  const decoded = new TextDecoder().decode(chunk);
1529
- const chunks = decoded.split(RECORD_SEPARATOR2);
2343
+ const chunks = decoded.split(RECORD_SEPARATOR3);
1530
2344
  for (const chunk2 of chunks) {
1531
2345
  if (chunk2) {
1532
2346
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1534,7 +2348,7 @@ var Workflow = class extends BaseResource {
1534
2348
  const parsedChunk = JSON.parse(newChunk);
1535
2349
  controller.enqueue(parsedChunk);
1536
2350
  failedChunk = void 0;
1537
- } catch (error) {
2351
+ } catch {
1538
2352
  failedChunk = newChunk;
1539
2353
  }
1540
2354
  }
@@ -1546,32 +2360,68 @@ var Workflow = class extends BaseResource {
1546
2360
  return response.body.pipeThrough(transformStream);
1547
2361
  }
1548
2362
  /**
1549
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1550
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1551
- * @returns Promise containing the workflow resume results
2363
+ * Streams agent builder action progress in real-time using VNext streaming.
2364
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1552
2365
  */
1553
- resumeAsync(params) {
2366
+ async streamVNext(params, runId) {
2367
+ const searchParams = new URLSearchParams();
2368
+ if (runId) {
2369
+ searchParams.set("runId", runId);
2370
+ }
1554
2371
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1555
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
2372
+ const { runtimeContext: _, ...actionParams } = params;
2373
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2374
+ const response = await this.request(url, {
1556
2375
  method: "POST",
1557
- body: {
1558
- step: params.step,
1559
- resumeData: params.resumeData,
1560
- runtimeContext
2376
+ body: { ...actionParams, runtimeContext },
2377
+ stream: true
2378
+ });
2379
+ if (!response.ok) {
2380
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2381
+ }
2382
+ if (!response.body) {
2383
+ throw new Error("Response body is null");
2384
+ }
2385
+ let failedChunk = void 0;
2386
+ const transformStream = new TransformStream({
2387
+ start() {
2388
+ },
2389
+ async transform(chunk, controller) {
2390
+ try {
2391
+ const decoded = new TextDecoder().decode(chunk);
2392
+ const chunks = decoded.split(RECORD_SEPARATOR3);
2393
+ for (const chunk2 of chunks) {
2394
+ if (chunk2) {
2395
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2396
+ try {
2397
+ const parsedChunk = JSON.parse(newChunk);
2398
+ controller.enqueue(parsedChunk);
2399
+ failedChunk = void 0;
2400
+ } catch {
2401
+ failedChunk = newChunk;
2402
+ }
2403
+ }
2404
+ }
2405
+ } catch {
2406
+ }
1561
2407
  }
1562
2408
  });
2409
+ return response.body.pipeThrough(transformStream);
1563
2410
  }
1564
2411
  /**
1565
- * Watches workflow transitions in real-time
1566
- * @param runId - Optional run ID to filter the watch stream
1567
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
2412
+ * Watches an existing agent builder action run by runId.
2413
+ * This is used for hot reload recovery - it loads the existing run state
2414
+ * and streams any remaining progress.
2415
+ * This calls `/api/agent-builder/:actionId/watch`.
1568
2416
  */
1569
- async watch({ runId }, onRecord) {
1570
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
2417
+ async watch({ runId, eventType }, onRecord) {
2418
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2419
+ const response = await this.request(url, {
2420
+ method: "GET",
1571
2421
  stream: true
1572
2422
  });
1573
2423
  if (!response.ok) {
1574
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
2424
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1575
2425
  }
1576
2426
  if (!response.body) {
1577
2427
  throw new Error("Response body is null");
@@ -1585,135 +2435,130 @@ var Workflow = class extends BaseResource {
1585
2435
  }
1586
2436
  }
1587
2437
  /**
1588
- * Creates a new ReadableStream from an iterable or async iterable of objects,
1589
- * serializing each as JSON and separating them with the record separator (\x1E).
1590
- *
1591
- * @param records - An iterable or async iterable of objects to stream
1592
- * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
2438
+ * Gets a specific action run by its ID.
2439
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
1593
2440
  */
1594
- static createRecordStream(records) {
1595
- const encoder = new TextEncoder();
1596
- return new ReadableStream({
1597
- async start(controller) {
1598
- try {
1599
- for await (const record of records) {
1600
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1601
- controller.enqueue(encoder.encode(json));
1602
- }
1603
- controller.close();
1604
- } catch (err) {
1605
- controller.error(err);
1606
- }
1607
- }
2441
+ async runById(runId) {
2442
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2443
+ return this.request(url, {
2444
+ method: "GET"
1608
2445
  });
1609
2446
  }
1610
- };
1611
-
1612
- // src/resources/a2a.ts
1613
- var A2A = class extends BaseResource {
1614
- constructor(options, agentId) {
1615
- super(options);
1616
- this.agentId = agentId;
1617
- }
1618
2447
  /**
1619
- * Get the agent card with metadata about the agent
1620
- * @returns Promise containing the agent card information
2448
+ * Gets details about this agent builder action.
2449
+ * This calls `/api/agent-builder/:actionId`.
1621
2450
  */
1622
- async getCard() {
1623
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2451
+ async details() {
2452
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2453
+ return result;
1624
2454
  }
1625
2455
  /**
1626
- * Send a message to the agent and get a response
1627
- * @param params - Parameters for the task
1628
- * @returns Promise containing the task response
2456
+ * Gets all runs for this agent builder action.
2457
+ * This calls `/api/agent-builder/:actionId/runs`.
1629
2458
  */
1630
- async sendMessage(params) {
1631
- const response = await this.request(`/a2a/${this.agentId}`, {
1632
- method: "POST",
1633
- body: {
1634
- method: "tasks/send",
1635
- params
1636
- }
2459
+ async runs(params) {
2460
+ const searchParams = new URLSearchParams();
2461
+ if (params?.fromDate) {
2462
+ searchParams.set("fromDate", params.fromDate.toISOString());
2463
+ }
2464
+ if (params?.toDate) {
2465
+ searchParams.set("toDate", params.toDate.toISOString());
2466
+ }
2467
+ if (params?.limit !== void 0) {
2468
+ searchParams.set("limit", String(params.limit));
2469
+ }
2470
+ if (params?.offset !== void 0) {
2471
+ searchParams.set("offset", String(params.offset));
2472
+ }
2473
+ if (params?.resourceId) {
2474
+ searchParams.set("resourceId", params.resourceId);
2475
+ }
2476
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2477
+ return this.request(url, {
2478
+ method: "GET"
1637
2479
  });
1638
- return { task: response.result };
1639
2480
  }
1640
2481
  /**
1641
- * Get the status and result of a task
1642
- * @param params - Parameters for querying the task
1643
- * @returns Promise containing the task response
2482
+ * Gets the execution result of an agent builder action run.
2483
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1644
2484
  */
1645
- async getTask(params) {
1646
- const response = await this.request(`/a2a/${this.agentId}`, {
1647
- method: "POST",
1648
- body: {
1649
- method: "tasks/get",
1650
- params
1651
- }
2485
+ async runExecutionResult(runId) {
2486
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2487
+ return this.request(url, {
2488
+ method: "GET"
1652
2489
  });
1653
- return response.result;
1654
2490
  }
1655
2491
  /**
1656
- * Cancel a running task
1657
- * @param params - Parameters identifying the task to cancel
1658
- * @returns Promise containing the task response
2492
+ * Cancels an agent builder action run.
2493
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1659
2494
  */
1660
- async cancelTask(params) {
1661
- return this.request(`/a2a/${this.agentId}`, {
1662
- method: "POST",
1663
- body: {
1664
- method: "tasks/cancel",
1665
- params
1666
- }
2495
+ async cancelRun(runId) {
2496
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2497
+ return this.request(url, {
2498
+ method: "POST"
1667
2499
  });
1668
2500
  }
1669
2501
  /**
1670
- * Send a message and subscribe to streaming updates (not fully implemented)
1671
- * @param params - Parameters for the task
1672
- * @returns Promise containing the task response
2502
+ * Sends an event to an agent builder action run.
2503
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1673
2504
  */
1674
- async sendAndSubscribe(params) {
1675
- return this.request(`/a2a/${this.agentId}`, {
2505
+ async sendRunEvent(params) {
2506
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2507
+ return this.request(url, {
1676
2508
  method: "POST",
1677
- body: {
1678
- method: "tasks/sendSubscribe",
1679
- params
1680
- },
1681
- stream: true
2509
+ body: { event: params.event, data: params.data }
1682
2510
  });
1683
2511
  }
1684
2512
  };
1685
2513
 
1686
- // src/resources/mcp-tool.ts
1687
- var MCPTool = class extends BaseResource {
1688
- serverId;
1689
- toolId;
1690
- constructor(options, serverId, toolId) {
2514
+ // src/resources/observability.ts
2515
+ var Observability = class extends BaseResource {
2516
+ constructor(options) {
1691
2517
  super(options);
1692
- this.serverId = serverId;
1693
- this.toolId = toolId;
1694
2518
  }
1695
2519
  /**
1696
- * Retrieves details about this specific tool from the MCP server.
1697
- * @returns Promise containing the tool's information (name, description, schema).
2520
+ * Retrieves a specific AI trace by ID
2521
+ * @param traceId - ID of the trace to retrieve
2522
+ * @returns Promise containing the AI trace with all its spans
1698
2523
  */
1699
- details() {
1700
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2524
+ getTrace(traceId) {
2525
+ return this.request(`/api/observability/traces/${traceId}`);
1701
2526
  }
1702
2527
  /**
1703
- * Executes this specific tool on the MCP server.
1704
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1705
- * @returns Promise containing the result of the tool execution.
2528
+ * Retrieves paginated list of AI traces with optional filtering
2529
+ * @param params - Parameters for pagination and filtering
2530
+ * @returns Promise containing paginated traces and pagination info
1706
2531
  */
1707
- execute(params) {
1708
- const body = {};
1709
- if (params.data !== void 0) body.data = params.data;
1710
- if (params.runtimeContext !== void 0) {
1711
- body.runtimeContext = params.runtimeContext;
2532
+ getTraces(params) {
2533
+ const { pagination, filters } = params;
2534
+ const { page, perPage, dateRange } = pagination || {};
2535
+ const { name, spanType, entityId, entityType } = filters || {};
2536
+ const searchParams = new URLSearchParams();
2537
+ if (page !== void 0) {
2538
+ searchParams.set("page", String(page));
1712
2539
  }
1713
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1714
- method: "POST",
1715
- body: Object.keys(body).length > 0 ? body : void 0
1716
- });
2540
+ if (perPage !== void 0) {
2541
+ searchParams.set("perPage", String(perPage));
2542
+ }
2543
+ if (name) {
2544
+ searchParams.set("name", name);
2545
+ }
2546
+ if (spanType !== void 0) {
2547
+ searchParams.set("spanType", String(spanType));
2548
+ }
2549
+ if (entityId && entityType) {
2550
+ searchParams.set("entityId", entityId);
2551
+ searchParams.set("entityType", entityType);
2552
+ }
2553
+ if (dateRange) {
2554
+ const dateRangeStr = JSON.stringify({
2555
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2556
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2557
+ });
2558
+ searchParams.set("dateRange", dateRangeStr);
2559
+ }
2560
+ const queryString = searchParams.toString();
2561
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
1717
2562
  }
1718
2563
  };
1719
2564
 
@@ -1781,7 +2626,7 @@ var NetworkMemoryThread = class extends BaseResource {
1781
2626
  };
1782
2627
 
1783
2628
  // src/resources/vNextNetwork.ts
1784
- var RECORD_SEPARATOR3 = "";
2629
+ var RECORD_SEPARATOR4 = "";
1785
2630
  var VNextNetwork = class extends BaseResource {
1786
2631
  constructor(options, networkId) {
1787
2632
  super(options);
@@ -1833,7 +2678,7 @@ var VNextNetwork = class extends BaseResource {
1833
2678
  if (done && !value) continue;
1834
2679
  try {
1835
2680
  const decoded = value ? new TextDecoder().decode(value) : "";
1836
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2681
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR4);
1837
2682
  buffer = chunks.pop() || "";
1838
2683
  for (const chunk of chunks) {
1839
2684
  if (chunk) {
@@ -1920,8 +2765,10 @@ var VNextNetwork = class extends BaseResource {
1920
2765
 
1921
2766
  // src/client.ts
1922
2767
  var MastraClient = class extends BaseResource {
2768
+ observability;
1923
2769
  constructor(options) {
1924
2770
  super(options);
2771
+ this.observability = new Observability(options);
1925
2772
  }
1926
2773
  /**
1927
2774
  * Retrieves all available agents
@@ -1930,21 +2777,6 @@ var MastraClient = class extends BaseResource {
1930
2777
  getAgents() {
1931
2778
  return this.request("/api/agents");
1932
2779
  }
1933
- async getAGUI({ resourceId }) {
1934
- const agents = await this.getAgents();
1935
- return Object.entries(agents).reduce(
1936
- (acc, [agentId]) => {
1937
- const agent = this.getAgent(agentId);
1938
- acc[agentId] = new AGUIAdapter({
1939
- agentId,
1940
- agent,
1941
- resourceId
1942
- });
1943
- return acc;
1944
- },
1945
- {}
1946
- );
1947
- }
1948
2780
  /**
1949
2781
  * Gets an agent instance by ID
1950
2782
  * @param agentId - ID of the agent to retrieve
@@ -2050,7 +2882,7 @@ var MastraClient = class extends BaseResource {
2050
2882
  * @returns Tool instance
2051
2883
  */
2052
2884
  getTool(toolId) {
2053
- return new Tool2(this.options, toolId);
2885
+ return new Tool(this.options, toolId);
2054
2886
  }
2055
2887
  /**
2056
2888
  * Retrieves all available legacy workflows
@@ -2082,6 +2914,20 @@ var MastraClient = class extends BaseResource {
2082
2914
  getWorkflow(workflowId) {
2083
2915
  return new Workflow(this.options, workflowId);
2084
2916
  }
2917
+ /**
2918
+ * Gets all available agent builder actions
2919
+ * @returns Promise containing map of action IDs to action details
2920
+ */
2921
+ getAgentBuilderActions() {
2922
+ return this.request("/api/agent-builder/");
2923
+ }
2924
+ /**
2925
+ * Gets an agent builder instance for executing agent-builder workflows
2926
+ * @returns AgentBuilder instance
2927
+ */
2928
+ getAgentBuilderAction(actionId) {
2929
+ return new AgentBuilder(this.options, actionId);
2930
+ }
2085
2931
  /**
2086
2932
  * Gets a vector instance by name
2087
2933
  * @param vectorName - Name of the vector to retrieve
@@ -2425,6 +3271,19 @@ var MastraClient = class extends BaseResource {
2425
3271
  body: params
2426
3272
  });
2427
3273
  }
3274
+ /**
3275
+ * Retrieves model providers with available keys
3276
+ * @returns Promise containing model providers with available keys
3277
+ */
3278
+ getModelProviders() {
3279
+ return this.request(`/api/model-providers`);
3280
+ }
3281
+ getAITrace(traceId) {
3282
+ return this.observability.getTrace(traceId);
3283
+ }
3284
+ getAITraces(params) {
3285
+ return this.observability.getTraces(params);
3286
+ }
2428
3287
  };
2429
3288
 
2430
3289
  exports.MastraClient = MastraClient;