@mastra/client-js 0.0.0-update-scorers-api-20250801170445 → 0.0.0-usechat-duplicate-20251016110554

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 (89) hide show
  1. package/CHANGELOG.md +1050 -3
  2. package/README.md +6 -8
  3. package/dist/client.d.ts +57 -44
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/index.cjs +1735 -850
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1734 -851
  10. package/dist/index.js.map +1 -1
  11. package/dist/resources/a2a.d.ts +15 -18
  12. package/dist/resources/a2a.d.ts.map +1 -1
  13. package/dist/resources/agent-builder.d.ts +160 -0
  14. package/dist/resources/agent-builder.d.ts.map +1 -0
  15. package/dist/resources/agent.d.ts +89 -17
  16. package/dist/resources/agent.d.ts.map +1 -1
  17. package/dist/resources/base.d.ts +1 -1
  18. package/dist/resources/base.d.ts.map +1 -1
  19. package/dist/resources/index.d.ts +10 -10
  20. package/dist/resources/index.d.ts.map +1 -1
  21. package/dist/resources/mcp-tool.d.ts +4 -3
  22. package/dist/resources/mcp-tool.d.ts.map +1 -1
  23. package/dist/resources/memory-thread.d.ts +3 -3
  24. package/dist/resources/memory-thread.d.ts.map +1 -1
  25. package/dist/resources/network-memory-thread.d.ts +3 -3
  26. package/dist/resources/network-memory-thread.d.ts.map +1 -1
  27. package/dist/resources/observability.d.ts +35 -0
  28. package/dist/resources/observability.d.ts.map +1 -0
  29. package/dist/resources/tool.d.ts +4 -3
  30. package/dist/resources/tool.d.ts.map +1 -1
  31. package/dist/resources/vector.d.ts +7 -4
  32. package/dist/resources/vector.d.ts.map +1 -1
  33. package/dist/resources/workflow.d.ts +129 -14
  34. package/dist/resources/workflow.d.ts.map +1 -1
  35. package/dist/tools.d.ts +22 -0
  36. package/dist/tools.d.ts.map +1 -0
  37. package/dist/types.d.ts +100 -43
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/utils/index.d.ts +2 -0
  40. package/dist/utils/index.d.ts.map +1 -1
  41. package/dist/utils/process-client-tools.d.ts.map +1 -1
  42. package/dist/utils/process-mastra-stream.d.ts +11 -0
  43. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  44. package/dist/utils/zod-to-json-schema.d.ts +2 -104
  45. package/dist/utils/zod-to-json-schema.d.ts.map +1 -1
  46. package/package.json +24 -16
  47. package/dist/adapters/agui.d.ts +0 -23
  48. package/dist/adapters/agui.d.ts.map +0 -1
  49. package/dist/resources/legacy-workflow.d.ts +0 -87
  50. package/dist/resources/legacy-workflow.d.ts.map +0 -1
  51. package/dist/resources/network.d.ts +0 -30
  52. package/dist/resources/network.d.ts.map +0 -1
  53. package/dist/resources/vNextNetwork.d.ts +0 -42
  54. package/dist/resources/vNextNetwork.d.ts.map +0 -1
  55. package/eslint.config.js +0 -6
  56. package/integration-tests/agui-adapter.test.ts +0 -122
  57. package/integration-tests/package.json +0 -18
  58. package/integration-tests/src/mastra/index.ts +0 -35
  59. package/integration-tests/vitest.config.ts +0 -9
  60. package/src/adapters/agui.test.ts +0 -322
  61. package/src/adapters/agui.ts +0 -239
  62. package/src/client.ts +0 -623
  63. package/src/example.ts +0 -95
  64. package/src/index.test.ts +0 -1226
  65. package/src/index.ts +0 -3
  66. package/src/resources/a2a.ts +0 -88
  67. package/src/resources/agent.ts +0 -785
  68. package/src/resources/base.ts +0 -76
  69. package/src/resources/index.ts +0 -10
  70. package/src/resources/legacy-workflow.ts +0 -242
  71. package/src/resources/mcp-tool.ts +0 -48
  72. package/src/resources/memory-thread.test.ts +0 -285
  73. package/src/resources/memory-thread.ts +0 -99
  74. package/src/resources/network-memory-thread.test.ts +0 -269
  75. package/src/resources/network-memory-thread.ts +0 -81
  76. package/src/resources/network.ts +0 -86
  77. package/src/resources/tool.ts +0 -45
  78. package/src/resources/vNextNetwork.ts +0 -194
  79. package/src/resources/vector.ts +0 -83
  80. package/src/resources/workflow.ts +0 -410
  81. package/src/types.ts +0 -502
  82. package/src/utils/index.ts +0 -11
  83. package/src/utils/process-client-tools.ts +0 -32
  84. package/src/utils/zod-to-json-schema.ts +0 -10
  85. package/src/v2-messages.test.ts +0 -180
  86. package/tsconfig.build.json +0 -9
  87. package/tsconfig.json +0 -5
  88. package/tsup.config.ts +0 -22
  89. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,209 +1,55 @@
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
- for (const message of messages) {
155
- if (message.role === "assistant") {
156
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
157
- for (const toolCall of message.toolCalls ?? []) {
158
- parts.push({
159
- type: "tool-call",
160
- toolCallId: toolCall.id,
161
- toolName: toolCall.function.name,
162
- args: JSON.parse(toolCall.function.arguments)
163
- });
164
- }
165
- result.push({
166
- role: "assistant",
167
- content: parts
168
- });
169
- if (message.toolCalls?.length) {
170
- result.push({
171
- role: "tool",
172
- content: message.toolCalls.map((toolCall) => ({
173
- type: "tool-result",
174
- toolCallId: toolCall.id,
175
- toolName: toolCall.function.name,
176
- result: JSON.parse(toolCall.function.arguments)
177
- }))
178
- });
179
- }
180
- } else if (message.role === "user") {
181
- result.push({
182
- role: "user",
183
- content: message.content || ""
184
- });
185
- } else if (message.role === "tool") {
186
- result.push({
187
- role: "tool",
188
- content: [
189
- {
190
- type: "tool-result",
191
- toolCallId: message.toolCallId,
192
- toolName: "unknown",
193
- result: message.content
194
- }
195
- ]
196
- });
197
- }
24
+ function base64RuntimeContext(runtimeContext) {
25
+ if (runtimeContext) {
26
+ return btoa(JSON.stringify(runtimeContext));
198
27
  }
199
- return result;
28
+ return void 0;
29
+ }
30
+ function runtimeContextQueryString(runtimeContext) {
31
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
32
+ if (!runtimeContextParam) return "";
33
+ const searchParams = new URLSearchParams();
34
+ searchParams.set("runtimeContext", runtimeContextParam);
35
+ const queryString = searchParams.toString();
36
+ return queryString ? `?${queryString}` : "";
37
+ }
38
+ function isZodType(value) {
39
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
200
40
  }
201
41
  function zodToJsonSchema(zodSchema) {
202
- if (!(zodSchema instanceof zod.ZodSchema)) {
42
+ if (!isZodType(zodSchema)) {
203
43
  return zodSchema;
204
44
  }
205
- return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
45
+ if ("toJSONSchema" in zod.z) {
46
+ const fn = "toJSONSchema";
47
+ return zod.z[fn].call(zod.z, zodSchema);
48
+ }
49
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "relative" });
206
50
  }
51
+
52
+ // src/utils/process-client-tools.ts
207
53
  function processClientTools(clientTools) {
208
54
  if (!clientTools) {
209
55
  return void 0;
@@ -232,6 +78,60 @@ function processClientTools(clientTools) {
232
78
  );
233
79
  }
234
80
 
81
+ // src/utils/process-mastra-stream.ts
82
+ async function sharedProcessMastraStream({
83
+ stream,
84
+ onChunk
85
+ }) {
86
+ const reader = stream.getReader();
87
+ const decoder = new TextDecoder();
88
+ let buffer = "";
89
+ try {
90
+ while (true) {
91
+ const { done, value } = await reader.read();
92
+ if (done) break;
93
+ buffer += decoder.decode(value, { stream: true });
94
+ const lines = buffer.split("\n\n");
95
+ buffer = lines.pop() || "";
96
+ for (const line of lines) {
97
+ if (line.startsWith("data: ")) {
98
+ const data = line.slice(6);
99
+ if (data === "[DONE]") {
100
+ console.info("\u{1F3C1} Stream finished");
101
+ return;
102
+ }
103
+ try {
104
+ const json = JSON.parse(data);
105
+ await onChunk(json);
106
+ } catch (error) {
107
+ console.error("\u274C JSON parse error:", error, "Data:", data);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ } finally {
113
+ reader.releaseLock();
114
+ }
115
+ }
116
+ async function processMastraNetworkStream({
117
+ stream,
118
+ onChunk
119
+ }) {
120
+ return sharedProcessMastraStream({
121
+ stream,
122
+ onChunk
123
+ });
124
+ }
125
+ async function processMastraStream({
126
+ stream,
127
+ onChunk
128
+ }) {
129
+ return sharedProcessMastraStream({
130
+ stream,
131
+ onChunk
132
+ });
133
+ }
134
+
235
135
  // src/resources/base.ts
236
136
  var BaseResource = class {
237
137
  options;
@@ -246,7 +146,7 @@ var BaseResource = class {
246
146
  */
247
147
  async request(path, options = {}) {
248
148
  let lastError = null;
249
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
149
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
250
150
  let delay = backoffMs;
251
151
  for (let attempt = 0; attempt <= retries; attempt++) {
252
152
  try {
@@ -260,6 +160,7 @@ var BaseResource = class {
260
160
  // 'x-mastra-client-type': 'js',
261
161
  },
262
162
  signal: this.options.abortSignal,
163
+ credentials: options.credentials ?? credentials,
263
164
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
264
165
  });
265
166
  if (!response.ok) {
@@ -292,14 +193,62 @@ var BaseResource = class {
292
193
  throw lastError || new Error("Request failed");
293
194
  }
294
195
  };
295
- function parseClientRuntimeContext(runtimeContext$1) {
296
- if (runtimeContext$1) {
297
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
298
- return Object.fromEntries(runtimeContext$1.entries());
196
+
197
+ // src/resources/agent.ts
198
+ async function executeToolCallAndRespond({
199
+ response,
200
+ params,
201
+ runId,
202
+ resourceId,
203
+ threadId,
204
+ runtimeContext,
205
+ respondFn
206
+ }) {
207
+ if (response.finishReason === "tool-calls") {
208
+ const toolCalls = response.toolCalls;
209
+ if (!toolCalls || !Array.isArray(toolCalls)) {
210
+ return response;
211
+ }
212
+ for (const toolCall of toolCalls) {
213
+ const clientTool = params.clientTools?.[toolCall.toolName];
214
+ if (clientTool && clientTool.execute) {
215
+ const result = await clientTool.execute(
216
+ {
217
+ context: toolCall?.args,
218
+ runId,
219
+ resourceId,
220
+ threadId,
221
+ runtimeContext,
222
+ tracingContext: { currentSpan: void 0 },
223
+ suspend: async () => {
224
+ }
225
+ },
226
+ {
227
+ messages: response.messages,
228
+ toolCallId: toolCall?.toolCallId
229
+ }
230
+ );
231
+ const updatedMessages = [
232
+ ...response.response.messages || [],
233
+ {
234
+ role: "tool",
235
+ content: [
236
+ {
237
+ type: "tool-result",
238
+ toolCallId: toolCall.toolCallId,
239
+ toolName: toolCall.toolName,
240
+ result
241
+ }
242
+ ]
243
+ }
244
+ ];
245
+ return respondFn({
246
+ ...params,
247
+ messages: updatedMessages
248
+ });
249
+ }
299
250
  }
300
- return runtimeContext$1;
301
251
  }
302
- return void 0;
303
252
  }
304
253
  var AgentVoice = class extends BaseResource {
305
254
  constructor(options, agentId) {
@@ -342,17 +291,21 @@ var AgentVoice = class extends BaseResource {
342
291
  }
343
292
  /**
344
293
  * Get available speakers for the agent's voice provider
294
+ * @param runtimeContext - Optional runtime context to pass as query parameter
295
+ * @param runtimeContext - Optional runtime context to pass as query parameter
345
296
  * @returns Promise containing list of available speakers
346
297
  */
347
- getSpeakers() {
348
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
298
+ getSpeakers(runtimeContext) {
299
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
349
300
  }
350
301
  /**
351
302
  * Get the listener configuration for the agent's voice provider
303
+ * @param runtimeContext - Optional runtime context to pass as query parameter
304
+ * @param runtimeContext - Optional runtime context to pass as query parameter
352
305
  * @returns Promise containing a check if the agent has listening capabilities
353
306
  */
354
- getListener() {
355
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
307
+ getListener(runtimeContext) {
308
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
356
309
  }
357
310
  };
358
311
  var Agent = class extends BaseResource {
@@ -364,12 +317,13 @@ var Agent = class extends BaseResource {
364
317
  voice;
365
318
  /**
366
319
  * Retrieves details about the agent
320
+ * @param runtimeContext - Optional runtime context to pass as query parameter
367
321
  * @returns Promise containing agent details including model and instructions
368
322
  */
369
- details() {
370
- return this.request(`/api/agents/${this.agentId}`);
323
+ details(runtimeContext) {
324
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
371
325
  }
372
- async generate(params) {
326
+ async generateLegacy(params) {
373
327
  const processedParams = {
374
328
  ...params,
375
329
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -379,7 +333,7 @@ var Agent = class extends BaseResource {
379
333
  };
380
334
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
381
335
  const response = await this.request(
382
- `/api/agents/${this.agentId}/generate`,
336
+ `/api/agents/${this.agentId}/generate-legacy`,
383
337
  {
384
338
  method: "POST",
385
339
  body: processedParams
@@ -394,17 +348,22 @@ var Agent = class extends BaseResource {
394
348
  const clientTool = params.clientTools?.[toolCall.toolName];
395
349
  if (clientTool && clientTool.execute) {
396
350
  const result = await clientTool.execute(
397
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
351
+ {
352
+ context: toolCall?.args,
353
+ runId,
354
+ resourceId,
355
+ threadId,
356
+ runtimeContext,
357
+ tracingContext: { currentSpan: void 0 },
358
+ suspend: async () => {
359
+ }
360
+ },
398
361
  {
399
362
  messages: response.messages,
400
363
  toolCallId: toolCall?.toolCallId
401
364
  }
402
365
  );
403
366
  const updatedMessages = [
404
- {
405
- role: "user",
406
- content: params.messages
407
- },
408
367
  ...response.response.messages,
409
368
  {
410
369
  role: "tool",
@@ -427,6 +386,47 @@ var Agent = class extends BaseResource {
427
386
  }
428
387
  return response;
429
388
  }
389
+ async generate(messagesOrParams, options) {
390
+ let params;
391
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
392
+ params = messagesOrParams;
393
+ } else {
394
+ params = {
395
+ messages: messagesOrParams,
396
+ ...options
397
+ };
398
+ }
399
+ const processedParams = {
400
+ ...params,
401
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
402
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
403
+ clientTools: processClientTools(params.clientTools),
404
+ structuredOutput: params.structuredOutput ? {
405
+ ...params.structuredOutput,
406
+ schema: zodToJsonSchema(params.structuredOutput.schema)
407
+ } : void 0
408
+ };
409
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
410
+ const response = await this.request(
411
+ `/api/agents/${this.agentId}/generate`,
412
+ {
413
+ method: "POST",
414
+ body: processedParams
415
+ }
416
+ );
417
+ if (response.finishReason === "tool-calls") {
418
+ return executeToolCallAndRespond({
419
+ response,
420
+ params,
421
+ runId,
422
+ resourceId,
423
+ threadId,
424
+ runtimeContext,
425
+ respondFn: this.generate.bind(this)
426
+ });
427
+ }
428
+ return response;
429
+ }
430
430
  async processChatResponse({
431
431
  stream,
432
432
  update,
@@ -694,7 +694,7 @@ var Agent = class extends BaseResource {
694
694
  * @param params - Stream parameters including prompt
695
695
  * @returns Promise containing the enhanced Response object with processDataStream method
696
696
  */
697
- async stream(params) {
697
+ async streamLegacy(params) {
698
698
  const processedParams = {
699
699
  ...params,
700
700
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -703,7 +703,7 @@ var Agent = class extends BaseResource {
703
703
  clientTools: processClientTools(params.clientTools)
704
704
  };
705
705
  const { readable, writable } = new TransformStream();
706
- const response = await this.processStreamResponse(processedParams, writable);
706
+ const response = await this.processStreamResponseLegacy(processedParams, writable);
707
707
  const streamResponse = new Response(readable, {
708
708
  status: response.status,
709
709
  statusText: response.statusText,
@@ -717,9 +717,267 @@ var Agent = class extends BaseResource {
717
717
  };
718
718
  return streamResponse;
719
719
  }
720
- /**
721
- * Processes the stream response and handles tool calls
722
- */
720
+ async processChatResponse_vNext({
721
+ stream,
722
+ update,
723
+ onToolCall,
724
+ onFinish,
725
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
726
+ lastMessage
727
+ }) {
728
+ const replaceLastMessage = lastMessage?.role === "assistant";
729
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
730
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
731
+ return Math.max(max, toolInvocation.step ?? 0);
732
+ }, 0) ?? 0) : 0;
733
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
734
+ id: uuid.v4(),
735
+ createdAt: getCurrentDate(),
736
+ role: "assistant",
737
+ content: "",
738
+ parts: []
739
+ };
740
+ let currentTextPart = void 0;
741
+ let currentReasoningPart = void 0;
742
+ let currentReasoningTextDetail = void 0;
743
+ function updateToolInvocationPart(toolCallId, invocation) {
744
+ const part = message.parts.find(
745
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
746
+ );
747
+ if (part != null) {
748
+ part.toolInvocation = invocation;
749
+ } else {
750
+ message.parts.push({
751
+ type: "tool-invocation",
752
+ toolInvocation: invocation
753
+ });
754
+ }
755
+ }
756
+ const data = [];
757
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
758
+ const partialToolCalls = {};
759
+ let usage = {
760
+ completionTokens: NaN,
761
+ promptTokens: NaN,
762
+ totalTokens: NaN
763
+ };
764
+ let finishReason = "unknown";
765
+ function execUpdate() {
766
+ const copiedData = [...data];
767
+ if (messageAnnotations?.length) {
768
+ message.annotations = messageAnnotations;
769
+ }
770
+ const copiedMessage = {
771
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
772
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
773
+ ...structuredClone(message),
774
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
775
+ // hashing approach by default to detect changes, but it only works for shallow
776
+ // changes. This is why we need to add a revision id to ensure that the message
777
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
778
+ // forwarded to rendering):
779
+ revisionId: uuid.v4()
780
+ };
781
+ update({
782
+ message: copiedMessage,
783
+ data: copiedData,
784
+ replaceLastMessage
785
+ });
786
+ }
787
+ await processMastraStream({
788
+ stream,
789
+ // TODO: casting as any here because the stream types were all typed as any before in core.
790
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
791
+ onChunk: async (chunk) => {
792
+ switch (chunk.type) {
793
+ case "tripwire": {
794
+ message.parts.push({
795
+ type: "text",
796
+ text: chunk.payload.tripwireReason
797
+ });
798
+ execUpdate();
799
+ break;
800
+ }
801
+ case "step-start": {
802
+ if (!replaceLastMessage) {
803
+ message.id = chunk.payload.messageId;
804
+ }
805
+ message.parts.push({ type: "step-start" });
806
+ execUpdate();
807
+ break;
808
+ }
809
+ case "text-delta": {
810
+ if (currentTextPart == null) {
811
+ currentTextPart = {
812
+ type: "text",
813
+ text: chunk.payload.text
814
+ };
815
+ message.parts.push(currentTextPart);
816
+ } else {
817
+ currentTextPart.text += chunk.payload.text;
818
+ }
819
+ message.content += chunk.payload.text;
820
+ execUpdate();
821
+ break;
822
+ }
823
+ case "reasoning-delta": {
824
+ if (currentReasoningTextDetail == null) {
825
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
826
+ if (currentReasoningPart != null) {
827
+ currentReasoningPart.details.push(currentReasoningTextDetail);
828
+ }
829
+ } else {
830
+ currentReasoningTextDetail.text += chunk.payload.text;
831
+ }
832
+ if (currentReasoningPart == null) {
833
+ currentReasoningPart = {
834
+ type: "reasoning",
835
+ reasoning: chunk.payload.text,
836
+ details: [currentReasoningTextDetail]
837
+ };
838
+ message.parts.push(currentReasoningPart);
839
+ } else {
840
+ currentReasoningPart.reasoning += chunk.payload.text;
841
+ }
842
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
843
+ execUpdate();
844
+ break;
845
+ }
846
+ case "file": {
847
+ message.parts.push({
848
+ type: "file",
849
+ mimeType: chunk.payload.mimeType,
850
+ data: chunk.payload.data
851
+ });
852
+ execUpdate();
853
+ break;
854
+ }
855
+ case "source": {
856
+ message.parts.push({
857
+ type: "source",
858
+ source: chunk.payload.source
859
+ });
860
+ execUpdate();
861
+ break;
862
+ }
863
+ case "tool-call": {
864
+ const invocation = {
865
+ state: "call",
866
+ step,
867
+ ...chunk.payload
868
+ };
869
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
870
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
871
+ } else {
872
+ if (message.toolInvocations == null) {
873
+ message.toolInvocations = [];
874
+ }
875
+ message.toolInvocations.push(invocation);
876
+ }
877
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
878
+ execUpdate();
879
+ if (onToolCall) {
880
+ const result = await onToolCall({ toolCall: chunk.payload });
881
+ if (result != null) {
882
+ const invocation2 = {
883
+ state: "result",
884
+ step,
885
+ ...chunk.payload,
886
+ result
887
+ };
888
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
889
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
890
+ execUpdate();
891
+ }
892
+ }
893
+ }
894
+ case "tool-call-input-streaming-start": {
895
+ if (message.toolInvocations == null) {
896
+ message.toolInvocations = [];
897
+ }
898
+ partialToolCalls[chunk.payload.toolCallId] = {
899
+ text: "",
900
+ step,
901
+ toolName: chunk.payload.toolName,
902
+ index: message.toolInvocations.length
903
+ };
904
+ const invocation = {
905
+ state: "partial-call",
906
+ step,
907
+ toolCallId: chunk.payload.toolCallId,
908
+ toolName: chunk.payload.toolName,
909
+ args: chunk.payload.args
910
+ };
911
+ message.toolInvocations.push(invocation);
912
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
913
+ execUpdate();
914
+ break;
915
+ }
916
+ case "tool-call-delta": {
917
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
918
+ partialToolCall.text += chunk.payload.argsTextDelta;
919
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
920
+ const invocation = {
921
+ state: "partial-call",
922
+ step: partialToolCall.step,
923
+ toolCallId: chunk.payload.toolCallId,
924
+ toolName: partialToolCall.toolName,
925
+ args: partialArgs
926
+ };
927
+ message.toolInvocations[partialToolCall.index] = invocation;
928
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
929
+ execUpdate();
930
+ break;
931
+ }
932
+ case "tool-result": {
933
+ const toolInvocations = message.toolInvocations;
934
+ if (toolInvocations == null) {
935
+ throw new Error("tool_result must be preceded by a tool_call");
936
+ }
937
+ const toolInvocationIndex = toolInvocations.findIndex(
938
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
939
+ );
940
+ if (toolInvocationIndex === -1) {
941
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
942
+ }
943
+ const invocation = {
944
+ ...toolInvocations[toolInvocationIndex],
945
+ state: "result",
946
+ ...chunk.payload
947
+ };
948
+ toolInvocations[toolInvocationIndex] = invocation;
949
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
950
+ execUpdate();
951
+ break;
952
+ }
953
+ case "error": {
954
+ throw new Error(chunk.payload.error);
955
+ }
956
+ case "data": {
957
+ data.push(...chunk.payload.data);
958
+ execUpdate();
959
+ break;
960
+ }
961
+ case "step-finish": {
962
+ step += 1;
963
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
964
+ currentReasoningPart = void 0;
965
+ currentReasoningTextDetail = void 0;
966
+ execUpdate();
967
+ break;
968
+ }
969
+ case "finish": {
970
+ finishReason = chunk.payload.stepResult.reason;
971
+ if (chunk.payload.usage != null) {
972
+ usage = chunk.payload.usage;
973
+ }
974
+ break;
975
+ }
976
+ }
977
+ }
978
+ });
979
+ onFinish?.({ message, finishReason, usage });
980
+ }
723
981
  async processStreamResponse(processedParams, writable) {
724
982
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
725
983
  method: "POST",
@@ -733,12 +991,30 @@ var Agent = class extends BaseResource {
733
991
  let toolCalls = [];
734
992
  let messages = [];
735
993
  const [streamForWritable, streamForProcessing] = response.body.tee();
736
- streamForWritable.pipeTo(writable, {
737
- preventClose: true
738
- }).catch((error) => {
994
+ streamForWritable.pipeTo(
995
+ new WritableStream({
996
+ async write(chunk) {
997
+ let writer;
998
+ try {
999
+ writer = writable.getWriter();
1000
+ const text = new TextDecoder().decode(chunk);
1001
+ const lines = text.split("\n\n");
1002
+ const readableLines = lines.filter((line) => line !== "[DONE]").join("\n\n");
1003
+ await writer.write(new TextEncoder().encode(readableLines));
1004
+ } catch {
1005
+ await writer?.write(chunk);
1006
+ } finally {
1007
+ writer?.releaseLock();
1008
+ }
1009
+ }
1010
+ }),
1011
+ {
1012
+ preventClose: true
1013
+ }
1014
+ ).catch((error) => {
739
1015
  console.error("Error piping to writable stream:", error);
740
1016
  });
741
- this.processChatResponse({
1017
+ this.processChatResponse_vNext({
742
1018
  stream: streamForProcessing,
743
1019
  update: ({ message }) => {
744
1020
  const existingIndex = messages.findIndex((m) => m.id === message.id);
@@ -754,23 +1030,30 @@ var Agent = class extends BaseResource {
754
1030
  if (toolCall) {
755
1031
  toolCalls.push(toolCall);
756
1032
  }
1033
+ let shouldExecuteClientTool = false;
757
1034
  for (const toolCall2 of toolCalls) {
758
1035
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
759
1036
  if (clientTool && clientTool.execute) {
1037
+ shouldExecuteClientTool = true;
760
1038
  const result = await clientTool.execute(
761
1039
  {
762
1040
  context: toolCall2?.args,
763
1041
  runId: processedParams.runId,
764
1042
  resourceId: processedParams.resourceId,
765
1043
  threadId: processedParams.threadId,
766
- runtimeContext: processedParams.runtimeContext
1044
+ runtimeContext: processedParams.runtimeContext,
1045
+ // TODO: Pass proper tracing context when client-js supports tracing
1046
+ tracingContext: { currentSpan: void 0 },
1047
+ suspend: async () => {
1048
+ }
767
1049
  },
768
1050
  {
769
1051
  messages: response.messages,
770
1052
  toolCallId: toolCall2?.toolCallId
771
1053
  }
772
1054
  );
773
- const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1055
+ const lastMessageRaw = messages[messages.length - 1];
1056
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
774
1057
  const toolInvocationPart = lastMessage?.parts?.find(
775
1058
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
776
1059
  );
@@ -788,9 +1071,177 @@ var Agent = class extends BaseResource {
788
1071
  toolInvocation.state = "result";
789
1072
  toolInvocation.result = result;
790
1073
  }
791
- const writer = writable.getWriter();
792
- try {
793
- await writer.write(
1074
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1075
+ this.processStreamResponse(
1076
+ {
1077
+ ...processedParams,
1078
+ messages: updatedMessages
1079
+ },
1080
+ writable
1081
+ ).catch((error) => {
1082
+ console.error("Error processing stream response:", error);
1083
+ });
1084
+ }
1085
+ }
1086
+ if (!shouldExecuteClientTool) {
1087
+ setTimeout(() => {
1088
+ writable.close();
1089
+ }, 0);
1090
+ }
1091
+ } else {
1092
+ setTimeout(() => {
1093
+ writable.close();
1094
+ }, 0);
1095
+ }
1096
+ },
1097
+ lastMessage: void 0
1098
+ }).catch((error) => {
1099
+ console.error("Error processing stream response:", error);
1100
+ });
1101
+ } catch (error) {
1102
+ console.error("Error processing stream response:", error);
1103
+ }
1104
+ return response;
1105
+ }
1106
+ async network(params) {
1107
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1108
+ method: "POST",
1109
+ body: params,
1110
+ stream: true
1111
+ });
1112
+ if (!response.body) {
1113
+ throw new Error("No response body");
1114
+ }
1115
+ const streamResponse = new Response(response.body, {
1116
+ status: response.status,
1117
+ statusText: response.statusText,
1118
+ headers: response.headers
1119
+ });
1120
+ streamResponse.processDataStream = async ({
1121
+ onChunk
1122
+ }) => {
1123
+ await processMastraNetworkStream({
1124
+ stream: streamResponse.body,
1125
+ onChunk
1126
+ });
1127
+ };
1128
+ return streamResponse;
1129
+ }
1130
+ async stream(messagesOrParams, options) {
1131
+ let params;
1132
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1133
+ params = messagesOrParams;
1134
+ } else {
1135
+ params = {
1136
+ messages: messagesOrParams,
1137
+ ...options
1138
+ };
1139
+ }
1140
+ const processedParams = {
1141
+ ...params,
1142
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1143
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1144
+ clientTools: processClientTools(params.clientTools),
1145
+ structuredOutput: params.structuredOutput ? {
1146
+ ...params.structuredOutput,
1147
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1148
+ } : void 0
1149
+ };
1150
+ const { readable, writable } = new TransformStream();
1151
+ const response = await this.processStreamResponse(processedParams, writable);
1152
+ const streamResponse = new Response(readable, {
1153
+ status: response.status,
1154
+ statusText: response.statusText,
1155
+ headers: response.headers
1156
+ });
1157
+ streamResponse.processDataStream = async ({
1158
+ onChunk
1159
+ }) => {
1160
+ await processMastraStream({
1161
+ stream: streamResponse.body,
1162
+ onChunk
1163
+ });
1164
+ };
1165
+ return streamResponse;
1166
+ }
1167
+ /**
1168
+ * Processes the stream response and handles tool calls
1169
+ */
1170
+ async processStreamResponseLegacy(processedParams, writable) {
1171
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1172
+ method: "POST",
1173
+ body: processedParams,
1174
+ stream: true
1175
+ });
1176
+ if (!response.body) {
1177
+ throw new Error("No response body");
1178
+ }
1179
+ try {
1180
+ let toolCalls = [];
1181
+ let messages = [];
1182
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1183
+ streamForWritable.pipeTo(writable, {
1184
+ preventClose: true
1185
+ }).catch((error) => {
1186
+ console.error("Error piping to writable stream:", error);
1187
+ });
1188
+ this.processChatResponse({
1189
+ stream: streamForProcessing,
1190
+ update: ({ message }) => {
1191
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1192
+ if (existingIndex !== -1) {
1193
+ messages[existingIndex] = message;
1194
+ } else {
1195
+ messages.push(message);
1196
+ }
1197
+ },
1198
+ onFinish: async ({ finishReason, message }) => {
1199
+ if (finishReason === "tool-calls") {
1200
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1201
+ if (toolCall) {
1202
+ toolCalls.push(toolCall);
1203
+ }
1204
+ for (const toolCall2 of toolCalls) {
1205
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1206
+ if (clientTool && clientTool.execute) {
1207
+ const result = await clientTool.execute(
1208
+ {
1209
+ context: toolCall2?.args,
1210
+ runId: processedParams.runId,
1211
+ resourceId: processedParams.resourceId,
1212
+ threadId: processedParams.threadId,
1213
+ runtimeContext: processedParams.runtimeContext,
1214
+ // TODO: Pass proper tracing context when client-js supports tracing
1215
+ tracingContext: { currentSpan: void 0 },
1216
+ suspend: async () => {
1217
+ }
1218
+ },
1219
+ {
1220
+ messages: response.messages,
1221
+ toolCallId: toolCall2?.toolCallId
1222
+ }
1223
+ );
1224
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1225
+ const toolInvocationPart = lastMessage?.parts?.find(
1226
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1227
+ );
1228
+ if (toolInvocationPart) {
1229
+ toolInvocationPart.toolInvocation = {
1230
+ ...toolInvocationPart.toolInvocation,
1231
+ state: "result",
1232
+ result
1233
+ };
1234
+ }
1235
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1236
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1237
+ );
1238
+ if (toolInvocation) {
1239
+ toolInvocation.state = "result";
1240
+ toolInvocation.result = result;
1241
+ }
1242
+ const writer = writable.getWriter();
1243
+ try {
1244
+ await writer.write(
794
1245
  new TextEncoder().encode(
795
1246
  "a:" + JSON.stringify({
796
1247
  toolCallId: toolCall2.toolCallId,
@@ -801,12 +1252,10 @@ var Agent = class extends BaseResource {
801
1252
  } finally {
802
1253
  writer.releaseLock();
803
1254
  }
804
- const originalMessages = processedParams.messages;
805
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
806
- this.processStreamResponse(
1255
+ this.processStreamResponseLegacy(
807
1256
  {
808
1257
  ...processedParams,
809
- messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1258
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
810
1259
  },
811
1260
  writable
812
1261
  ).catch((error) => {
@@ -832,10 +1281,11 @@ var Agent = class extends BaseResource {
832
1281
  /**
833
1282
  * Gets details about a specific tool available to the agent
834
1283
  * @param toolId - ID of the tool to retrieve
1284
+ * @param runtimeContext - Optional runtime context to pass as query parameter
835
1285
  * @returns Promise containing tool details
836
1286
  */
837
- getTool(toolId) {
838
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1287
+ getTool(toolId, runtimeContext) {
1288
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
839
1289
  }
840
1290
  /**
841
1291
  * Executes a tool for the agent
@@ -846,7 +1296,7 @@ var Agent = class extends BaseResource {
846
1296
  executeTool(toolId, params) {
847
1297
  const body = {
848
1298
  data: params.data,
849
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1299
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
850
1300
  };
851
1301
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
852
1302
  method: "POST",
@@ -855,73 +1305,58 @@ var Agent = class extends BaseResource {
855
1305
  }
856
1306
  /**
857
1307
  * Retrieves evaluation results for the agent
1308
+ * @param runtimeContext - Optional runtime context to pass as query parameter
858
1309
  * @returns Promise containing agent evaluations
859
1310
  */
860
- evals() {
861
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1311
+ evals(runtimeContext) {
1312
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
862
1313
  }
863
1314
  /**
864
1315
  * Retrieves live evaluation results for the agent
1316
+ * @param runtimeContext - Optional runtime context to pass as query parameter
865
1317
  * @returns Promise containing live agent evaluations
866
1318
  */
867
- liveEvals() {
868
- return this.request(`/api/agents/${this.agentId}/evals/live`);
869
- }
870
- };
871
- var Network = class extends BaseResource {
872
- constructor(options, networkId) {
873
- super(options);
874
- this.networkId = networkId;
1319
+ liveEvals(runtimeContext) {
1320
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
875
1321
  }
876
1322
  /**
877
- * Retrieves details about the network
878
- * @returns Promise containing network details
1323
+ * Updates the model for the agent
1324
+ * @param params - Parameters for updating the model
1325
+ * @returns Promise containing the updated model
879
1326
  */
880
- details() {
881
- return this.request(`/api/networks/${this.networkId}`);
1327
+ updateModel(params) {
1328
+ return this.request(`/api/agents/${this.agentId}/model`, {
1329
+ method: "POST",
1330
+ body: params
1331
+ });
882
1332
  }
883
1333
  /**
884
- * Generates a response from the agent
885
- * @param params - Generation parameters including prompt
886
- * @returns Promise containing the generated response
1334
+ * Updates the model for the agent in the model list
1335
+ * @param params - Parameters for updating the model
1336
+ * @returns Promise containing the updated model
887
1337
  */
888
- generate(params) {
889
- const processedParams = {
890
- ...params,
891
- output: zodToJsonSchema(params.output),
892
- experimental_output: zodToJsonSchema(params.experimental_output)
893
- };
894
- return this.request(`/api/networks/${this.networkId}/generate`, {
1338
+ updateModelInModelList({ modelConfigId, ...params }) {
1339
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
895
1340
  method: "POST",
896
- body: processedParams
1341
+ body: params
897
1342
  });
898
1343
  }
899
1344
  /**
900
- * Streams a response from the agent
901
- * @param params - Stream parameters including prompt
902
- * @returns Promise containing the enhanced Response object with processDataStream method
1345
+ * Reorders the models for the agent
1346
+ * @param params - Parameters for reordering the model list
1347
+ * @returns Promise containing the updated model list
903
1348
  */
904
- async stream(params) {
905
- const processedParams = {
906
- ...params,
907
- output: zodToJsonSchema(params.output),
908
- experimental_output: zodToJsonSchema(params.experimental_output)
909
- };
910
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1349
+ reorderModelList(params) {
1350
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
911
1351
  method: "POST",
912
- body: processedParams,
913
- stream: true
1352
+ body: params
914
1353
  });
915
- if (!response.body) {
916
- throw new Error("No response body");
917
- }
918
- response.processDataStream = async (options = {}) => {
919
- await uiUtils.processDataStream({
920
- stream: response.body,
921
- ...options
922
- });
923
- };
924
- return response;
1354
+ }
1355
+ async generateVNext(_messagesOrParams, _options) {
1356
+ throw new Error("generateVNext has been renamed to generate. Please use generate instead.");
1357
+ }
1358
+ async streamVNext(_messagesOrParams, _options) {
1359
+ throw new Error("streamVNext has been renamed to stream. Please use stream instead.");
925
1360
  }
926
1361
  };
927
1362
 
@@ -1012,10 +1447,13 @@ var Vector = class extends BaseResource {
1012
1447
  /**
1013
1448
  * Retrieves details about a specific vector index
1014
1449
  * @param indexName - Name of the index to get details for
1450
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1015
1451
  * @returns Promise containing vector index details
1016
1452
  */
1017
- details(indexName) {
1018
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1453
+ details(indexName, runtimeContext) {
1454
+ return this.request(
1455
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1456
+ );
1019
1457
  }
1020
1458
  /**
1021
1459
  * Deletes a vector index
@@ -1029,10 +1467,11 @@ var Vector = class extends BaseResource {
1029
1467
  }
1030
1468
  /**
1031
1469
  * Retrieves a list of all available indexes
1470
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1032
1471
  * @returns Promise containing array of index names
1033
1472
  */
1034
- getIndexes() {
1035
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1473
+ getIndexes(runtimeContext) {
1474
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
1036
1475
  }
1037
1476
  /**
1038
1477
  * Creates a new vector index
@@ -1069,26 +1508,109 @@ var Vector = class extends BaseResource {
1069
1508
  }
1070
1509
  };
1071
1510
 
1072
- // src/resources/legacy-workflow.ts
1511
+ // src/resources/tool.ts
1512
+ var Tool = class extends BaseResource {
1513
+ constructor(options, toolId) {
1514
+ super(options);
1515
+ this.toolId = toolId;
1516
+ }
1517
+ /**
1518
+ * Retrieves details about the tool
1519
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1520
+ * @returns Promise containing tool details including description and schemas
1521
+ */
1522
+ details(runtimeContext) {
1523
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1524
+ }
1525
+ /**
1526
+ * Executes the tool with the provided parameters
1527
+ * @param params - Parameters required for tool execution
1528
+ * @returns Promise containing the tool execution results
1529
+ */
1530
+ execute(params) {
1531
+ const url = new URLSearchParams();
1532
+ if (params.runId) {
1533
+ url.set("runId", params.runId);
1534
+ }
1535
+ const body = {
1536
+ data: params.data,
1537
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1538
+ };
1539
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1540
+ method: "POST",
1541
+ body
1542
+ });
1543
+ }
1544
+ };
1545
+
1546
+ // src/resources/workflow.ts
1073
1547
  var RECORD_SEPARATOR = "";
1074
- var LegacyWorkflow = class extends BaseResource {
1548
+ var Workflow = class extends BaseResource {
1075
1549
  constructor(options, workflowId) {
1076
1550
  super(options);
1077
1551
  this.workflowId = workflowId;
1078
1552
  }
1079
1553
  /**
1080
- * Retrieves details about the legacy workflow
1081
- * @returns Promise containing legacy workflow details including steps and graphs
1554
+ * Creates an async generator that processes a readable stream and yields workflow records
1555
+ * separated by the Record Separator character (\x1E)
1556
+ *
1557
+ * @param stream - The readable stream to process
1558
+ * @returns An async generator that yields parsed records
1559
+ */
1560
+ async *streamProcessor(stream) {
1561
+ const reader = stream.getReader();
1562
+ let doneReading = false;
1563
+ let buffer = "";
1564
+ try {
1565
+ while (!doneReading) {
1566
+ const { done, value } = await reader.read();
1567
+ doneReading = done;
1568
+ if (done && !value) continue;
1569
+ try {
1570
+ const decoded = value ? new TextDecoder().decode(value) : "";
1571
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1572
+ buffer = chunks.pop() || "";
1573
+ for (const chunk of chunks) {
1574
+ if (chunk) {
1575
+ if (typeof chunk === "string") {
1576
+ try {
1577
+ const parsedChunk = JSON.parse(chunk);
1578
+ yield parsedChunk;
1579
+ } catch {
1580
+ }
1581
+ }
1582
+ }
1583
+ }
1584
+ } catch {
1585
+ }
1586
+ }
1587
+ if (buffer) {
1588
+ try {
1589
+ yield JSON.parse(buffer);
1590
+ } catch {
1591
+ }
1592
+ }
1593
+ } finally {
1594
+ reader.cancel().catch(() => {
1595
+ });
1596
+ }
1597
+ }
1598
+ /**
1599
+ * Retrieves details about the workflow
1600
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1601
+ * @returns Promise containing workflow details including steps and graphs
1082
1602
  */
1083
- details() {
1084
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1603
+ details(runtimeContext) {
1604
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1085
1605
  }
1086
1606
  /**
1087
- * Retrieves all runs for a legacy workflow
1607
+ * Retrieves all runs for a workflow
1088
1608
  * @param params - Parameters for filtering runs
1089
- * @returns Promise containing legacy workflow runs array
1609
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1610
+ * @returns Promise containing workflow runs array
1090
1611
  */
1091
- runs(params) {
1612
+ runs(params, runtimeContext) {
1613
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1092
1614
  const searchParams = new URLSearchParams();
1093
1615
  if (params?.fromDate) {
1094
1616
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1096,296 +1618,43 @@ var LegacyWorkflow = class extends BaseResource {
1096
1618
  if (params?.toDate) {
1097
1619
  searchParams.set("toDate", params.toDate.toISOString());
1098
1620
  }
1099
- if (params?.limit) {
1621
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1100
1622
  searchParams.set("limit", String(params.limit));
1101
1623
  }
1102
- if (params?.offset) {
1624
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1103
1625
  searchParams.set("offset", String(params.offset));
1104
1626
  }
1105
1627
  if (params?.resourceId) {
1106
1628
  searchParams.set("resourceId", params.resourceId);
1107
1629
  }
1630
+ if (runtimeContextParam) {
1631
+ searchParams.set("runtimeContext", runtimeContextParam);
1632
+ }
1108
1633
  if (searchParams.size) {
1109
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1634
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1110
1635
  } else {
1111
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1112
- }
1113
- }
1114
- /**
1115
- * Creates a new legacy workflow run
1116
- * @returns Promise containing the generated run ID
1117
- */
1118
- createRun(params) {
1119
- const searchParams = new URLSearchParams();
1120
- if (!!params?.runId) {
1121
- searchParams.set("runId", params.runId);
1122
- }
1123
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1124
- method: "POST"
1125
- });
1126
- }
1127
- /**
1128
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1129
- * @param params - Object containing the runId and triggerData
1130
- * @returns Promise containing success message
1131
- */
1132
- start(params) {
1133
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1134
- method: "POST",
1135
- body: params?.triggerData
1136
- });
1137
- }
1138
- /**
1139
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1140
- * @param stepId - ID of the step to resume
1141
- * @param runId - ID of the legacy workflow run
1142
- * @param context - Context to resume the legacy workflow with
1143
- * @returns Promise containing the legacy workflow resume results
1144
- */
1145
- resume({
1146
- stepId,
1147
- runId,
1148
- context
1149
- }) {
1150
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1151
- method: "POST",
1152
- body: {
1153
- stepId,
1154
- context
1155
- }
1156
- });
1157
- }
1158
- /**
1159
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1160
- * @param params - Object containing the optional runId and triggerData
1161
- * @returns Promise containing the workflow execution results
1162
- */
1163
- startAsync(params) {
1164
- const searchParams = new URLSearchParams();
1165
- if (!!params?.runId) {
1166
- searchParams.set("runId", params.runId);
1167
- }
1168
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1169
- method: "POST",
1170
- body: params?.triggerData
1171
- });
1172
- }
1173
- /**
1174
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1175
- * @param params - Object containing the runId, stepId, and context
1176
- * @returns Promise containing the workflow resume results
1177
- */
1178
- resumeAsync(params) {
1179
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1180
- method: "POST",
1181
- body: {
1182
- stepId: params.stepId,
1183
- context: params.context
1184
- }
1185
- });
1186
- }
1187
- /**
1188
- * Creates an async generator that processes a readable stream and yields records
1189
- * separated by the Record Separator character (\x1E)
1190
- *
1191
- * @param stream - The readable stream to process
1192
- * @returns An async generator that yields parsed records
1193
- */
1194
- async *streamProcessor(stream) {
1195
- const reader = stream.getReader();
1196
- let doneReading = false;
1197
- let buffer = "";
1198
- try {
1199
- while (!doneReading) {
1200
- const { done, value } = await reader.read();
1201
- doneReading = done;
1202
- if (done && !value) continue;
1203
- try {
1204
- const decoded = value ? new TextDecoder().decode(value) : "";
1205
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1206
- buffer = chunks.pop() || "";
1207
- for (const chunk of chunks) {
1208
- if (chunk) {
1209
- if (typeof chunk === "string") {
1210
- try {
1211
- const parsedChunk = JSON.parse(chunk);
1212
- yield parsedChunk;
1213
- } catch {
1214
- }
1215
- }
1216
- }
1217
- }
1218
- } catch {
1219
- }
1220
- }
1221
- if (buffer) {
1222
- try {
1223
- yield JSON.parse(buffer);
1224
- } catch {
1225
- }
1226
- }
1227
- } finally {
1228
- reader.cancel().catch(() => {
1229
- });
1230
- }
1231
- }
1232
- /**
1233
- * Watches legacy workflow transitions in real-time
1234
- * @param runId - Optional run ID to filter the watch stream
1235
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1236
- */
1237
- async watch({ runId }, onRecord) {
1238
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1239
- stream: true
1240
- });
1241
- if (!response.ok) {
1242
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1243
- }
1244
- if (!response.body) {
1245
- throw new Error("Response body is null");
1246
- }
1247
- for await (const record of this.streamProcessor(response.body)) {
1248
- onRecord(record);
1249
- }
1250
- }
1251
- };
1252
-
1253
- // src/resources/tool.ts
1254
- var Tool2 = class extends BaseResource {
1255
- constructor(options, toolId) {
1256
- super(options);
1257
- this.toolId = toolId;
1258
- }
1259
- /**
1260
- * Retrieves details about the tool
1261
- * @returns Promise containing tool details including description and schemas
1262
- */
1263
- details() {
1264
- return this.request(`/api/tools/${this.toolId}`);
1265
- }
1266
- /**
1267
- * Executes the tool with the provided parameters
1268
- * @param params - Parameters required for tool execution
1269
- * @returns Promise containing the tool execution results
1270
- */
1271
- execute(params) {
1272
- const url = new URLSearchParams();
1273
- if (params.runId) {
1274
- url.set("runId", params.runId);
1275
- }
1276
- const body = {
1277
- data: params.data,
1278
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1279
- };
1280
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1281
- method: "POST",
1282
- body
1283
- });
1284
- }
1285
- };
1286
-
1287
- // src/resources/workflow.ts
1288
- var RECORD_SEPARATOR2 = "";
1289
- var Workflow = class extends BaseResource {
1290
- constructor(options, workflowId) {
1291
- super(options);
1292
- this.workflowId = workflowId;
1293
- }
1294
- /**
1295
- * Creates an async generator that processes a readable stream and yields workflow records
1296
- * separated by the Record Separator character (\x1E)
1297
- *
1298
- * @param stream - The readable stream to process
1299
- * @returns An async generator that yields parsed records
1300
- */
1301
- async *streamProcessor(stream) {
1302
- const reader = stream.getReader();
1303
- let doneReading = false;
1304
- let buffer = "";
1305
- try {
1306
- while (!doneReading) {
1307
- const { done, value } = await reader.read();
1308
- doneReading = done;
1309
- if (done && !value) continue;
1310
- try {
1311
- const decoded = value ? new TextDecoder().decode(value) : "";
1312
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1313
- buffer = chunks.pop() || "";
1314
- for (const chunk of chunks) {
1315
- if (chunk) {
1316
- if (typeof chunk === "string") {
1317
- try {
1318
- const parsedChunk = JSON.parse(chunk);
1319
- yield parsedChunk;
1320
- } catch {
1321
- }
1322
- }
1323
- }
1324
- }
1325
- } catch {
1326
- }
1327
- }
1328
- if (buffer) {
1329
- try {
1330
- yield JSON.parse(buffer);
1331
- } catch {
1332
- }
1333
- }
1334
- } finally {
1335
- reader.cancel().catch(() => {
1336
- });
1337
- }
1338
- }
1339
- /**
1340
- * Retrieves details about the workflow
1341
- * @returns Promise containing workflow details including steps and graphs
1342
- */
1343
- details() {
1344
- return this.request(`/api/workflows/${this.workflowId}`);
1345
- }
1346
- /**
1347
- * Retrieves all runs for a workflow
1348
- * @param params - Parameters for filtering runs
1349
- * @returns Promise containing workflow runs array
1350
- */
1351
- runs(params) {
1352
- const searchParams = new URLSearchParams();
1353
- if (params?.fromDate) {
1354
- searchParams.set("fromDate", params.fromDate.toISOString());
1355
- }
1356
- if (params?.toDate) {
1357
- searchParams.set("toDate", params.toDate.toISOString());
1358
- }
1359
- if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1360
- searchParams.set("limit", String(params.limit));
1361
- }
1362
- if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1363
- searchParams.set("offset", String(params.offset));
1364
- }
1365
- if (params?.resourceId) {
1366
- searchParams.set("resourceId", params.resourceId);
1367
- }
1368
- if (searchParams.size) {
1369
- return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1370
- } else {
1371
- return this.request(`/api/workflows/${this.workflowId}/runs`);
1636
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1372
1637
  }
1373
1638
  }
1374
1639
  /**
1375
1640
  * Retrieves a specific workflow run by its ID
1376
1641
  * @param runId - The ID of the workflow run to retrieve
1642
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1377
1643
  * @returns Promise containing the workflow run details
1378
1644
  */
1379
- runById(runId) {
1380
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1645
+ runById(runId, runtimeContext) {
1646
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1381
1647
  }
1382
1648
  /**
1383
1649
  * Retrieves the execution result for a specific workflow run by its ID
1384
1650
  * @param runId - The ID of the workflow run to retrieve the execution result for
1651
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1385
1652
  * @returns Promise containing the workflow run execution result
1386
1653
  */
1387
- runExecutionResult(runId) {
1388
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1654
+ runExecutionResult(runId, runtimeContext) {
1655
+ return this.request(
1656
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1657
+ );
1389
1658
  }
1390
1659
  /**
1391
1660
  * Cancels a specific workflow run by its ID
@@ -1408,27 +1677,83 @@ var Workflow = class extends BaseResource {
1408
1677
  body: { event: params.event, data: params.data }
1409
1678
  });
1410
1679
  }
1680
+ /**
1681
+ * @deprecated Use createRunAsync() instead.
1682
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1683
+ */
1684
+ async createRun(_params) {
1685
+ throw new Error(
1686
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
1687
+ );
1688
+ }
1411
1689
  /**
1412
1690
  * Creates a new workflow run
1413
1691
  * @param params - Optional object containing the optional runId
1414
- * @returns Promise containing the runId of the created run
1692
+ * @returns Promise containing the runId of the created run with methods to control execution
1415
1693
  */
1416
- createRun(params) {
1694
+ async createRunAsync(params) {
1417
1695
  const searchParams = new URLSearchParams();
1418
1696
  if (!!params?.runId) {
1419
1697
  searchParams.set("runId", params.runId);
1420
1698
  }
1421
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1422
- method: "POST"
1423
- });
1424
- }
1425
- /**
1426
- * Creates a new workflow run (alias for createRun)
1427
- * @param params - Optional object containing the optional runId
1428
- * @returns Promise containing the runId of the created run
1429
- */
1430
- createRunAsync(params) {
1431
- return this.createRun(params);
1699
+ const res = await this.request(
1700
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1701
+ {
1702
+ method: "POST"
1703
+ }
1704
+ );
1705
+ const runId = res.runId;
1706
+ return {
1707
+ runId,
1708
+ start: async (p) => {
1709
+ return this.start({
1710
+ runId,
1711
+ inputData: p.inputData,
1712
+ runtimeContext: p.runtimeContext,
1713
+ tracingOptions: p.tracingOptions
1714
+ });
1715
+ },
1716
+ startAsync: async (p) => {
1717
+ return this.startAsync({
1718
+ runId,
1719
+ inputData: p.inputData,
1720
+ runtimeContext: p.runtimeContext,
1721
+ tracingOptions: p.tracingOptions
1722
+ });
1723
+ },
1724
+ watch: async (onRecord) => {
1725
+ return this.watch({ runId }, onRecord);
1726
+ },
1727
+ stream: async (p) => {
1728
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1729
+ },
1730
+ resume: async (p) => {
1731
+ return this.resume({
1732
+ runId,
1733
+ step: p.step,
1734
+ resumeData: p.resumeData,
1735
+ runtimeContext: p.runtimeContext,
1736
+ tracingOptions: p.tracingOptions
1737
+ });
1738
+ },
1739
+ resumeAsync: async (p) => {
1740
+ return this.resumeAsync({
1741
+ runId,
1742
+ step: p.step,
1743
+ resumeData: p.resumeData,
1744
+ runtimeContext: p.runtimeContext,
1745
+ tracingOptions: p.tracingOptions
1746
+ });
1747
+ },
1748
+ resumeStreamVNext: async (p) => {
1749
+ return this.resumeStreamVNext({
1750
+ runId,
1751
+ step: p.step,
1752
+ resumeData: p.resumeData,
1753
+ runtimeContext: p.runtimeContext
1754
+ });
1755
+ }
1756
+ };
1432
1757
  }
1433
1758
  /**
1434
1759
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -1439,7 +1764,7 @@ var Workflow = class extends BaseResource {
1439
1764
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1440
1765
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1441
1766
  method: "POST",
1442
- body: { inputData: params?.inputData, runtimeContext }
1767
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1443
1768
  });
1444
1769
  }
1445
1770
  /**
@@ -1451,16 +1776,17 @@ var Workflow = class extends BaseResource {
1451
1776
  step,
1452
1777
  runId,
1453
1778
  resumeData,
1779
+ tracingOptions,
1454
1780
  ...rest
1455
1781
  }) {
1456
1782
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1457
1783
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1458
1784
  method: "POST",
1459
- stream: true,
1460
1785
  body: {
1461
1786
  step,
1462
1787
  resumeData,
1463
- runtimeContext
1788
+ runtimeContext,
1789
+ tracingOptions
1464
1790
  }
1465
1791
  });
1466
1792
  }
@@ -1477,7 +1803,7 @@ var Workflow = class extends BaseResource {
1477
1803
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1478
1804
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1479
1805
  method: "POST",
1480
- body: { inputData: params.inputData, runtimeContext }
1806
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1481
1807
  });
1482
1808
  }
1483
1809
  /**
@@ -1495,12 +1821,12 @@ var Workflow = class extends BaseResource {
1495
1821
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1496
1822
  {
1497
1823
  method: "POST",
1498
- body: { inputData: params.inputData, runtimeContext },
1824
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1499
1825
  stream: true
1500
1826
  }
1501
1827
  );
1502
1828
  if (!response.ok) {
1503
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1829
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1504
1830
  }
1505
1831
  if (!response.body) {
1506
1832
  throw new Error("Response body is null");
@@ -1512,7 +1838,7 @@ var Workflow = class extends BaseResource {
1512
1838
  async transform(chunk, controller) {
1513
1839
  try {
1514
1840
  const decoded = new TextDecoder().decode(chunk);
1515
- const chunks = decoded.split(RECORD_SEPARATOR2);
1841
+ const chunks = decoded.split(RECORD_SEPARATOR);
1516
1842
  for (const chunk2 of chunks) {
1517
1843
  if (chunk2) {
1518
1844
  const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
@@ -1520,7 +1846,7 @@ var Workflow = class extends BaseResource {
1520
1846
  const parsedChunk = JSON.parse(newChunk);
1521
1847
  controller.enqueue(parsedChunk);
1522
1848
  failedChunk = void 0;
1523
- } catch (error) {
1849
+ } catch {
1524
1850
  failedChunk = newChunk;
1525
1851
  }
1526
1852
  }
@@ -1532,20 +1858,225 @@ var Workflow = class extends BaseResource {
1532
1858
  return response.body.pipeThrough(transformStream);
1533
1859
  }
1534
1860
  /**
1535
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1536
- * @param params - Object containing the runId, step, resumeData and runtimeContext
1537
- * @returns Promise containing the workflow resume results
1861
+ * Observes workflow stream for a workflow run
1862
+ * @param params - Object containing the runId
1863
+ * @returns Promise containing the workflow execution results
1538
1864
  */
1539
- resumeAsync(params) {
1540
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1865
+ async observeStream(params) {
1866
+ const searchParams = new URLSearchParams();
1867
+ searchParams.set("runId", params.runId);
1868
+ const response = await this.request(
1869
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1870
+ {
1871
+ method: "POST",
1872
+ stream: true
1873
+ }
1874
+ );
1875
+ if (!response.ok) {
1876
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1877
+ }
1878
+ if (!response.body) {
1879
+ throw new Error("Response body is null");
1880
+ }
1881
+ let failedChunk = void 0;
1882
+ const transformStream = new TransformStream({
1883
+ start() {
1884
+ },
1885
+ async transform(chunk, controller) {
1886
+ try {
1887
+ const decoded = new TextDecoder().decode(chunk);
1888
+ const chunks = decoded.split(RECORD_SEPARATOR);
1889
+ for (const chunk2 of chunks) {
1890
+ if (chunk2) {
1891
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1892
+ try {
1893
+ const parsedChunk = JSON.parse(newChunk);
1894
+ controller.enqueue(parsedChunk);
1895
+ failedChunk = void 0;
1896
+ } catch {
1897
+ failedChunk = newChunk;
1898
+ }
1899
+ }
1900
+ }
1901
+ } catch {
1902
+ }
1903
+ }
1904
+ });
1905
+ return response.body.pipeThrough(transformStream);
1906
+ }
1907
+ /**
1908
+ * Starts a workflow run and returns a stream
1909
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1910
+ * @returns Promise containing the workflow execution results
1911
+ */
1912
+ async streamVNext(params) {
1913
+ const searchParams = new URLSearchParams();
1914
+ if (!!params?.runId) {
1915
+ searchParams.set("runId", params.runId);
1916
+ }
1917
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1918
+ const response = await this.request(
1919
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1920
+ {
1921
+ method: "POST",
1922
+ body: {
1923
+ inputData: params.inputData,
1924
+ runtimeContext,
1925
+ closeOnSuspend: params.closeOnSuspend,
1926
+ tracingOptions: params.tracingOptions
1927
+ },
1928
+ stream: true
1929
+ }
1930
+ );
1931
+ if (!response.ok) {
1932
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1933
+ }
1934
+ if (!response.body) {
1935
+ throw new Error("Response body is null");
1936
+ }
1937
+ let failedChunk = void 0;
1938
+ const transformStream = new TransformStream({
1939
+ start() {
1940
+ },
1941
+ async transform(chunk, controller) {
1942
+ try {
1943
+ const decoded = new TextDecoder().decode(chunk);
1944
+ const chunks = decoded.split(RECORD_SEPARATOR);
1945
+ for (const chunk2 of chunks) {
1946
+ if (chunk2) {
1947
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1948
+ try {
1949
+ const parsedChunk = JSON.parse(newChunk);
1950
+ controller.enqueue(parsedChunk);
1951
+ failedChunk = void 0;
1952
+ } catch {
1953
+ failedChunk = newChunk;
1954
+ }
1955
+ }
1956
+ }
1957
+ } catch {
1958
+ }
1959
+ }
1960
+ });
1961
+ return response.body.pipeThrough(transformStream);
1962
+ }
1963
+ /**
1964
+ * Observes workflow vNext stream for a workflow run
1965
+ * @param params - Object containing the runId
1966
+ * @returns Promise containing the workflow execution results
1967
+ */
1968
+ async observeStreamVNext(params) {
1969
+ const searchParams = new URLSearchParams();
1970
+ searchParams.set("runId", params.runId);
1971
+ const response = await this.request(
1972
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1973
+ {
1974
+ method: "POST",
1975
+ stream: true
1976
+ }
1977
+ );
1978
+ if (!response.ok) {
1979
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
1980
+ }
1981
+ if (!response.body) {
1982
+ throw new Error("Response body is null");
1983
+ }
1984
+ let failedChunk = void 0;
1985
+ const transformStream = new TransformStream({
1986
+ start() {
1987
+ },
1988
+ async transform(chunk, controller) {
1989
+ try {
1990
+ const decoded = new TextDecoder().decode(chunk);
1991
+ const chunks = decoded.split(RECORD_SEPARATOR);
1992
+ for (const chunk2 of chunks) {
1993
+ if (chunk2) {
1994
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1995
+ try {
1996
+ const parsedChunk = JSON.parse(newChunk);
1997
+ controller.enqueue(parsedChunk);
1998
+ failedChunk = void 0;
1999
+ } catch {
2000
+ failedChunk = newChunk;
2001
+ }
2002
+ }
2003
+ }
2004
+ } catch {
2005
+ }
2006
+ }
2007
+ });
2008
+ return response.body.pipeThrough(transformStream);
2009
+ }
2010
+ /**
2011
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
2012
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2013
+ * @returns Promise containing the workflow resume results
2014
+ */
2015
+ resumeAsync(params) {
2016
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1541
2017
  return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1542
2018
  method: "POST",
1543
2019
  body: {
1544
2020
  step: params.step,
1545
2021
  resumeData: params.resumeData,
1546
- runtimeContext
2022
+ runtimeContext,
2023
+ tracingOptions: params.tracingOptions
2024
+ }
2025
+ });
2026
+ }
2027
+ /**
2028
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
2029
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
2030
+ * @returns Promise containing the workflow resume results
2031
+ */
2032
+ async resumeStreamVNext(params) {
2033
+ const searchParams = new URLSearchParams();
2034
+ searchParams.set("runId", params.runId);
2035
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2036
+ const response = await this.request(
2037
+ `/api/workflows/${this.workflowId}/resume-stream?${searchParams.toString()}`,
2038
+ {
2039
+ method: "POST",
2040
+ body: {
2041
+ step: params.step,
2042
+ resumeData: params.resumeData,
2043
+ runtimeContext,
2044
+ tracingOptions: params.tracingOptions
2045
+ },
2046
+ stream: true
2047
+ }
2048
+ );
2049
+ if (!response.ok) {
2050
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
2051
+ }
2052
+ if (!response.body) {
2053
+ throw new Error("Response body is null");
2054
+ }
2055
+ let failedChunk = void 0;
2056
+ const transformStream = new TransformStream({
2057
+ start() {
2058
+ },
2059
+ async transform(chunk, controller) {
2060
+ try {
2061
+ const decoded = new TextDecoder().decode(chunk);
2062
+ const chunks = decoded.split(RECORD_SEPARATOR);
2063
+ for (const chunk2 of chunks) {
2064
+ if (chunk2) {
2065
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2066
+ try {
2067
+ const parsedChunk = JSON.parse(newChunk);
2068
+ controller.enqueue(parsedChunk);
2069
+ failedChunk = void 0;
2070
+ } catch {
2071
+ failedChunk = newChunk;
2072
+ }
2073
+ }
2074
+ }
2075
+ } catch {
2076
+ }
1547
2077
  }
1548
2078
  });
2079
+ return response.body.pipeThrough(transformStream);
1549
2080
  }
1550
2081
  /**
1551
2082
  * Watches workflow transitions in real-time
@@ -1583,7 +2114,7 @@ var Workflow = class extends BaseResource {
1583
2114
  async start(controller) {
1584
2115
  try {
1585
2116
  for await (const record of records) {
1586
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2117
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
1587
2118
  controller.enqueue(encoder.encode(json));
1588
2119
  }
1589
2120
  controller.close();
@@ -1606,99 +2137,546 @@ var A2A = class extends BaseResource {
1606
2137
  * @returns Promise containing the agent card information
1607
2138
  */
1608
2139
  async getCard() {
1609
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2140
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1610
2141
  }
1611
2142
  /**
1612
- * Send a message to the agent and get a response
2143
+ * Send a message to the agent and gets a message or task response
1613
2144
  * @param params - Parameters for the task
1614
- * @returns Promise containing the task response
2145
+ * @returns Promise containing the response
1615
2146
  */
1616
2147
  async sendMessage(params) {
1617
2148
  const response = await this.request(`/a2a/${this.agentId}`, {
1618
2149
  method: "POST",
1619
2150
  body: {
1620
- method: "tasks/send",
2151
+ method: "message/send",
2152
+ params
2153
+ }
2154
+ });
2155
+ return response;
2156
+ }
2157
+ /**
2158
+ * Sends a message to an agent to initiate/continue a task and subscribes
2159
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2160
+ * @param params - Parameters for the task
2161
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2162
+ */
2163
+ async sendStreamingMessage(params) {
2164
+ const response = await this.request(`/a2a/${this.agentId}`, {
2165
+ method: "POST",
2166
+ body: {
2167
+ method: "message/stream",
2168
+ params
2169
+ }
2170
+ });
2171
+ return response;
2172
+ }
2173
+ /**
2174
+ * Get the status and result of a task
2175
+ * @param params - Parameters for querying the task
2176
+ * @returns Promise containing the task response
2177
+ */
2178
+ async getTask(params) {
2179
+ const response = await this.request(`/a2a/${this.agentId}`, {
2180
+ method: "POST",
2181
+ body: {
2182
+ method: "tasks/get",
2183
+ params
2184
+ }
2185
+ });
2186
+ return response;
2187
+ }
2188
+ /**
2189
+ * Cancel a running task
2190
+ * @param params - Parameters identifying the task to cancel
2191
+ * @returns Promise containing the task response
2192
+ */
2193
+ async cancelTask(params) {
2194
+ return this.request(`/a2a/${this.agentId}`, {
2195
+ method: "POST",
2196
+ body: {
2197
+ method: "tasks/cancel",
1621
2198
  params
1622
2199
  }
1623
2200
  });
1624
- return { task: response.result };
2201
+ }
2202
+ };
2203
+
2204
+ // src/resources/mcp-tool.ts
2205
+ var MCPTool = class extends BaseResource {
2206
+ serverId;
2207
+ toolId;
2208
+ constructor(options, serverId, toolId) {
2209
+ super(options);
2210
+ this.serverId = serverId;
2211
+ this.toolId = toolId;
2212
+ }
2213
+ /**
2214
+ * Retrieves details about this specific tool from the MCP server.
2215
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2216
+ * @returns Promise containing the tool's information (name, description, schema).
2217
+ */
2218
+ details(runtimeContext) {
2219
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2220
+ }
2221
+ /**
2222
+ * Executes this specific tool on the MCP server.
2223
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2224
+ * @returns Promise containing the result of the tool execution.
2225
+ */
2226
+ execute(params) {
2227
+ const body = {};
2228
+ if (params.data !== void 0) body.data = params.data;
2229
+ if (params.runtimeContext !== void 0) {
2230
+ body.runtimeContext = params.runtimeContext;
2231
+ }
2232
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2233
+ method: "POST",
2234
+ body: Object.keys(body).length > 0 ? body : void 0
2235
+ });
2236
+ }
2237
+ };
2238
+
2239
+ // src/resources/agent-builder.ts
2240
+ var RECORD_SEPARATOR2 = "";
2241
+ var AgentBuilder = class extends BaseResource {
2242
+ constructor(options, actionId) {
2243
+ super(options);
2244
+ this.actionId = actionId;
2245
+ }
2246
+ // Helper function to transform workflow result to action result
2247
+ transformWorkflowResult(result) {
2248
+ if (result.status === "success") {
2249
+ return {
2250
+ success: result.result.success || false,
2251
+ applied: result.result.applied || false,
2252
+ branchName: result.result.branchName,
2253
+ message: result.result.message || "Agent builder action completed",
2254
+ validationResults: result.result.validationResults,
2255
+ error: result.result.error,
2256
+ errors: result.result.errors,
2257
+ stepResults: result.result.stepResults
2258
+ };
2259
+ } else if (result.status === "failed") {
2260
+ return {
2261
+ success: false,
2262
+ applied: false,
2263
+ message: `Agent builder action failed: ${result.error.message}`,
2264
+ error: result.error.message
2265
+ };
2266
+ } else {
2267
+ return {
2268
+ success: false,
2269
+ applied: false,
2270
+ message: "Agent builder action was suspended",
2271
+ error: "Workflow suspended - manual intervention required"
2272
+ };
2273
+ }
2274
+ }
2275
+ /**
2276
+ * @deprecated Use createRunAsync() instead.
2277
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2278
+ */
2279
+ async createRun(_params) {
2280
+ throw new Error(
2281
+ "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = agentBuilder.createRun();\n After: const run = await agentBuilder.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
2282
+ );
2283
+ }
2284
+ /**
2285
+ * Creates a new agent builder action run and returns the runId.
2286
+ * This calls `/api/agent-builder/:actionId/create-run`.
2287
+ */
2288
+ async createRunAsync(params) {
2289
+ const searchParams = new URLSearchParams();
2290
+ if (!!params?.runId) {
2291
+ searchParams.set("runId", params.runId);
2292
+ }
2293
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2294
+ return this.request(url, {
2295
+ method: "POST"
2296
+ });
2297
+ }
2298
+ /**
2299
+ * Starts agent builder action asynchronously and waits for completion.
2300
+ * This calls `/api/agent-builder/:actionId/start-async`.
2301
+ */
2302
+ async startAsync(params, runId) {
2303
+ const searchParams = new URLSearchParams();
2304
+ if (runId) {
2305
+ searchParams.set("runId", runId);
2306
+ }
2307
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2308
+ const { runtimeContext: _, ...actionParams } = params;
2309
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2310
+ const result = await this.request(url, {
2311
+ method: "POST",
2312
+ body: { ...actionParams, runtimeContext }
2313
+ });
2314
+ return this.transformWorkflowResult(result);
2315
+ }
2316
+ /**
2317
+ * Starts an existing agent builder action run.
2318
+ * This calls `/api/agent-builder/:actionId/start`.
2319
+ */
2320
+ async startActionRun(params, runId) {
2321
+ const searchParams = new URLSearchParams();
2322
+ searchParams.set("runId", runId);
2323
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2324
+ const { runtimeContext: _, ...actionParams } = params;
2325
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2326
+ return this.request(url, {
2327
+ method: "POST",
2328
+ body: { ...actionParams, runtimeContext }
2329
+ });
2330
+ }
2331
+ /**
2332
+ * Resumes a suspended agent builder action step.
2333
+ * This calls `/api/agent-builder/:actionId/resume`.
2334
+ */
2335
+ async resume(params, runId) {
2336
+ const searchParams = new URLSearchParams();
2337
+ searchParams.set("runId", runId);
2338
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2339
+ const { runtimeContext: _, ...resumeParams } = params;
2340
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2341
+ return this.request(url, {
2342
+ method: "POST",
2343
+ body: { ...resumeParams, runtimeContext }
2344
+ });
2345
+ }
2346
+ /**
2347
+ * Resumes a suspended agent builder action step asynchronously.
2348
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2349
+ */
2350
+ async resumeAsync(params, runId) {
2351
+ const searchParams = new URLSearchParams();
2352
+ searchParams.set("runId", runId);
2353
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2354
+ const { runtimeContext: _, ...resumeParams } = params;
2355
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2356
+ const result = await this.request(url, {
2357
+ method: "POST",
2358
+ body: { ...resumeParams, runtimeContext }
2359
+ });
2360
+ return this.transformWorkflowResult(result);
2361
+ }
2362
+ /**
2363
+ * Creates an async generator that processes a readable stream and yields action records
2364
+ * separated by the Record Separator character (\x1E)
2365
+ *
2366
+ * @param stream - The readable stream to process
2367
+ * @returns An async generator that yields parsed records
2368
+ */
2369
+ async *streamProcessor(stream) {
2370
+ const reader = stream.getReader();
2371
+ let doneReading = false;
2372
+ let buffer = "";
2373
+ try {
2374
+ while (!doneReading) {
2375
+ const { done, value } = await reader.read();
2376
+ doneReading = done;
2377
+ if (done && !value) continue;
2378
+ try {
2379
+ const decoded = value ? new TextDecoder().decode(value) : "";
2380
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2381
+ buffer = chunks.pop() || "";
2382
+ for (const chunk of chunks) {
2383
+ if (chunk) {
2384
+ if (typeof chunk === "string") {
2385
+ try {
2386
+ const parsedChunk = JSON.parse(chunk);
2387
+ yield parsedChunk;
2388
+ } catch {
2389
+ }
2390
+ }
2391
+ }
2392
+ }
2393
+ } catch {
2394
+ }
2395
+ }
2396
+ if (buffer) {
2397
+ try {
2398
+ yield JSON.parse(buffer);
2399
+ } catch {
2400
+ }
2401
+ }
2402
+ } finally {
2403
+ reader.cancel().catch(() => {
2404
+ });
2405
+ }
2406
+ }
2407
+ /**
2408
+ * Streams agent builder action progress in real-time.
2409
+ * This calls `/api/agent-builder/:actionId/stream`.
2410
+ */
2411
+ async stream(params, runId) {
2412
+ const searchParams = new URLSearchParams();
2413
+ if (runId) {
2414
+ searchParams.set("runId", runId);
2415
+ }
2416
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2417
+ const { runtimeContext: _, ...actionParams } = params;
2418
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2419
+ const response = await this.request(url, {
2420
+ method: "POST",
2421
+ body: { ...actionParams, runtimeContext },
2422
+ stream: true
2423
+ });
2424
+ if (!response.ok) {
2425
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2426
+ }
2427
+ if (!response.body) {
2428
+ throw new Error("Response body is null");
2429
+ }
2430
+ let failedChunk = void 0;
2431
+ const transformStream = new TransformStream({
2432
+ start() {
2433
+ },
2434
+ async transform(chunk, controller) {
2435
+ try {
2436
+ const decoded = new TextDecoder().decode(chunk);
2437
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2438
+ for (const chunk2 of chunks) {
2439
+ if (chunk2) {
2440
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2441
+ try {
2442
+ const parsedChunk = JSON.parse(newChunk);
2443
+ controller.enqueue(parsedChunk);
2444
+ failedChunk = void 0;
2445
+ } catch {
2446
+ failedChunk = newChunk;
2447
+ }
2448
+ }
2449
+ }
2450
+ } catch {
2451
+ }
2452
+ }
2453
+ });
2454
+ return response.body.pipeThrough(transformStream);
2455
+ }
2456
+ /**
2457
+ * Streams agent builder action progress in real-time using VNext streaming.
2458
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2459
+ */
2460
+ async streamVNext(params, runId) {
2461
+ const searchParams = new URLSearchParams();
2462
+ if (runId) {
2463
+ searchParams.set("runId", runId);
2464
+ }
2465
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2466
+ const { runtimeContext: _, ...actionParams } = params;
2467
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2468
+ const response = await this.request(url, {
2469
+ method: "POST",
2470
+ body: { ...actionParams, runtimeContext },
2471
+ stream: true
2472
+ });
2473
+ if (!response.ok) {
2474
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2475
+ }
2476
+ if (!response.body) {
2477
+ throw new Error("Response body is null");
2478
+ }
2479
+ let failedChunk = void 0;
2480
+ const transformStream = new TransformStream({
2481
+ start() {
2482
+ },
2483
+ async transform(chunk, controller) {
2484
+ try {
2485
+ const decoded = new TextDecoder().decode(chunk);
2486
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2487
+ for (const chunk2 of chunks) {
2488
+ if (chunk2) {
2489
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2490
+ try {
2491
+ const parsedChunk = JSON.parse(newChunk);
2492
+ controller.enqueue(parsedChunk);
2493
+ failedChunk = void 0;
2494
+ } catch {
2495
+ failedChunk = newChunk;
2496
+ }
2497
+ }
2498
+ }
2499
+ } catch {
2500
+ }
2501
+ }
2502
+ });
2503
+ return response.body.pipeThrough(transformStream);
2504
+ }
2505
+ /**
2506
+ * Watches an existing agent builder action run by runId.
2507
+ * This is used for hot reload recovery - it loads the existing run state
2508
+ * and streams any remaining progress.
2509
+ * This calls `/api/agent-builder/:actionId/watch`.
2510
+ */
2511
+ async watch({ runId, eventType }, onRecord) {
2512
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2513
+ const response = await this.request(url, {
2514
+ method: "GET",
2515
+ stream: true
2516
+ });
2517
+ if (!response.ok) {
2518
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2519
+ }
2520
+ if (!response.body) {
2521
+ throw new Error("Response body is null");
2522
+ }
2523
+ for await (const record of this.streamProcessor(response.body)) {
2524
+ if (typeof record === "string") {
2525
+ onRecord(JSON.parse(record));
2526
+ } else {
2527
+ onRecord(record);
2528
+ }
2529
+ }
2530
+ }
2531
+ /**
2532
+ * Gets a specific action run by its ID.
2533
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2534
+ */
2535
+ async runById(runId) {
2536
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2537
+ return this.request(url, {
2538
+ method: "GET"
2539
+ });
2540
+ }
2541
+ /**
2542
+ * Gets details about this agent builder action.
2543
+ * This calls `/api/agent-builder/:actionId`.
2544
+ */
2545
+ async details() {
2546
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2547
+ return result;
2548
+ }
2549
+ /**
2550
+ * Gets all runs for this agent builder action.
2551
+ * This calls `/api/agent-builder/:actionId/runs`.
2552
+ */
2553
+ async runs(params) {
2554
+ const searchParams = new URLSearchParams();
2555
+ if (params?.fromDate) {
2556
+ searchParams.set("fromDate", params.fromDate.toISOString());
2557
+ }
2558
+ if (params?.toDate) {
2559
+ searchParams.set("toDate", params.toDate.toISOString());
2560
+ }
2561
+ if (params?.limit !== void 0) {
2562
+ searchParams.set("limit", String(params.limit));
2563
+ }
2564
+ if (params?.offset !== void 0) {
2565
+ searchParams.set("offset", String(params.offset));
2566
+ }
2567
+ if (params?.resourceId) {
2568
+ searchParams.set("resourceId", params.resourceId);
2569
+ }
2570
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2571
+ return this.request(url, {
2572
+ method: "GET"
2573
+ });
1625
2574
  }
1626
2575
  /**
1627
- * Get the status and result of a task
1628
- * @param params - Parameters for querying the task
1629
- * @returns Promise containing the task response
2576
+ * Gets the execution result of an agent builder action run.
2577
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
1630
2578
  */
1631
- async getTask(params) {
1632
- const response = await this.request(`/a2a/${this.agentId}`, {
1633
- method: "POST",
1634
- body: {
1635
- method: "tasks/get",
1636
- params
1637
- }
2579
+ async runExecutionResult(runId) {
2580
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2581
+ return this.request(url, {
2582
+ method: "GET"
1638
2583
  });
1639
- return response.result;
1640
2584
  }
1641
2585
  /**
1642
- * Cancel a running task
1643
- * @param params - Parameters identifying the task to cancel
1644
- * @returns Promise containing the task response
2586
+ * Cancels an agent builder action run.
2587
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
1645
2588
  */
1646
- async cancelTask(params) {
1647
- return this.request(`/a2a/${this.agentId}`, {
1648
- method: "POST",
1649
- body: {
1650
- method: "tasks/cancel",
1651
- params
1652
- }
2589
+ async cancelRun(runId) {
2590
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2591
+ return this.request(url, {
2592
+ method: "POST"
1653
2593
  });
1654
2594
  }
1655
2595
  /**
1656
- * Send a message and subscribe to streaming updates (not fully implemented)
1657
- * @param params - Parameters for the task
1658
- * @returns Promise containing the task response
2596
+ * Sends an event to an agent builder action run.
2597
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1659
2598
  */
1660
- async sendAndSubscribe(params) {
1661
- return this.request(`/a2a/${this.agentId}`, {
2599
+ async sendRunEvent(params) {
2600
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2601
+ return this.request(url, {
1662
2602
  method: "POST",
1663
- body: {
1664
- method: "tasks/sendSubscribe",
1665
- params
1666
- },
1667
- stream: true
2603
+ body: { event: params.event, data: params.data }
1668
2604
  });
1669
2605
  }
1670
2606
  };
1671
2607
 
1672
- // src/resources/mcp-tool.ts
1673
- var MCPTool = class extends BaseResource {
1674
- serverId;
1675
- toolId;
1676
- constructor(options, serverId, toolId) {
2608
+ // src/resources/observability.ts
2609
+ var Observability = class extends BaseResource {
2610
+ constructor(options) {
1677
2611
  super(options);
1678
- this.serverId = serverId;
1679
- this.toolId = toolId;
1680
2612
  }
1681
2613
  /**
1682
- * Retrieves details about this specific tool from the MCP server.
1683
- * @returns Promise containing the tool's information (name, description, schema).
2614
+ * Retrieves a specific AI trace by ID
2615
+ * @param traceId - ID of the trace to retrieve
2616
+ * @returns Promise containing the AI trace with all its spans
1684
2617
  */
1685
- details() {
1686
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2618
+ getTrace(traceId) {
2619
+ return this.request(`/api/observability/traces/${traceId}`);
1687
2620
  }
1688
2621
  /**
1689
- * Executes this specific tool on the MCP server.
1690
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1691
- * @returns Promise containing the result of the tool execution.
2622
+ * Retrieves paginated list of AI traces with optional filtering
2623
+ * @param params - Parameters for pagination and filtering
2624
+ * @returns Promise containing paginated traces and pagination info
1692
2625
  */
1693
- execute(params) {
1694
- const body = {};
1695
- if (params.data !== void 0) body.data = params.data;
1696
- if (params.runtimeContext !== void 0) {
1697
- body.runtimeContext = params.runtimeContext;
2626
+ getTraces(params) {
2627
+ const { pagination, filters } = params;
2628
+ const { page, perPage, dateRange } = pagination || {};
2629
+ const { name, spanType, entityId, entityType } = filters || {};
2630
+ const searchParams = new URLSearchParams();
2631
+ if (page !== void 0) {
2632
+ searchParams.set("page", String(page));
1698
2633
  }
1699
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2634
+ if (perPage !== void 0) {
2635
+ searchParams.set("perPage", String(perPage));
2636
+ }
2637
+ if (name) {
2638
+ searchParams.set("name", name);
2639
+ }
2640
+ if (spanType !== void 0) {
2641
+ searchParams.set("spanType", String(spanType));
2642
+ }
2643
+ if (entityId && entityType) {
2644
+ searchParams.set("entityId", entityId);
2645
+ searchParams.set("entityType", entityType);
2646
+ }
2647
+ if (dateRange) {
2648
+ const dateRangeStr = JSON.stringify({
2649
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2650
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2651
+ });
2652
+ searchParams.set("dateRange", dateRangeStr);
2653
+ }
2654
+ const queryString = searchParams.toString();
2655
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2656
+ }
2657
+ /**
2658
+ * Retrieves scores by trace ID and span ID
2659
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2660
+ * @returns Promise containing scores and pagination info
2661
+ */
2662
+ getScoresBySpan(params) {
2663
+ const { traceId, spanId, page, perPage } = params;
2664
+ const searchParams = new URLSearchParams();
2665
+ if (page !== void 0) {
2666
+ searchParams.set("page", String(page));
2667
+ }
2668
+ if (perPage !== void 0) {
2669
+ searchParams.set("perPage", String(perPage));
2670
+ }
2671
+ const queryString = searchParams.toString();
2672
+ return this.request(
2673
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2674
+ );
2675
+ }
2676
+ score(params) {
2677
+ return this.request(`/api/observability/traces/score`, {
1700
2678
  method: "POST",
1701
- body: Object.keys(body).length > 0 ? body : void 0
2679
+ body: { ...params }
1702
2680
  });
1703
2681
  }
1704
2682
  };
@@ -1766,170 +2744,26 @@ var NetworkMemoryThread = class extends BaseResource {
1766
2744
  }
1767
2745
  };
1768
2746
 
1769
- // src/resources/vNextNetwork.ts
1770
- var RECORD_SEPARATOR3 = "";
1771
- var VNextNetwork = class extends BaseResource {
1772
- constructor(options, networkId) {
1773
- super(options);
1774
- this.networkId = networkId;
1775
- }
1776
- /**
1777
- * Retrieves details about the network
1778
- * @returns Promise containing vNext network details
1779
- */
1780
- details() {
1781
- return this.request(`/api/networks/v-next/${this.networkId}`);
1782
- }
1783
- /**
1784
- * Generates a response from the v-next network
1785
- * @param params - Generation parameters including message
1786
- * @returns Promise containing the generated response
1787
- */
1788
- generate(params) {
1789
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1790
- method: "POST",
1791
- body: {
1792
- ...params,
1793
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1794
- }
1795
- });
1796
- }
1797
- /**
1798
- * Generates a response from the v-next network using multiple primitives
1799
- * @param params - Generation parameters including message
1800
- * @returns Promise containing the generated response
1801
- */
1802
- loop(params) {
1803
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1804
- method: "POST",
1805
- body: {
1806
- ...params,
1807
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1808
- }
1809
- });
1810
- }
1811
- async *streamProcessor(stream) {
1812
- const reader = stream.getReader();
1813
- let doneReading = false;
1814
- let buffer = "";
1815
- try {
1816
- while (!doneReading) {
1817
- const { done, value } = await reader.read();
1818
- doneReading = done;
1819
- if (done && !value) continue;
1820
- try {
1821
- const decoded = value ? new TextDecoder().decode(value) : "";
1822
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1823
- buffer = chunks.pop() || "";
1824
- for (const chunk of chunks) {
1825
- if (chunk) {
1826
- if (typeof chunk === "string") {
1827
- try {
1828
- const parsedChunk = JSON.parse(chunk);
1829
- yield parsedChunk;
1830
- } catch {
1831
- }
1832
- }
1833
- }
1834
- }
1835
- } catch {
1836
- }
1837
- }
1838
- if (buffer) {
1839
- try {
1840
- yield JSON.parse(buffer);
1841
- } catch {
1842
- }
1843
- }
1844
- } finally {
1845
- reader.cancel().catch(() => {
1846
- });
1847
- }
1848
- }
1849
- /**
1850
- * Streams a response from the v-next network
1851
- * @param params - Stream parameters including message
1852
- * @returns Promise containing the results
1853
- */
1854
- async stream(params, onRecord) {
1855
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1856
- method: "POST",
1857
- body: {
1858
- ...params,
1859
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1860
- },
1861
- stream: true
1862
- });
1863
- if (!response.ok) {
1864
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1865
- }
1866
- if (!response.body) {
1867
- throw new Error("Response body is null");
1868
- }
1869
- for await (const record of this.streamProcessor(response.body)) {
1870
- if (typeof record === "string") {
1871
- onRecord(JSON.parse(record));
1872
- } else {
1873
- onRecord(record);
1874
- }
1875
- }
1876
- }
1877
- /**
1878
- * Streams a response from the v-next network loop
1879
- * @param params - Stream parameters including message
1880
- * @returns Promise containing the results
1881
- */
1882
- async loopStream(params, onRecord) {
1883
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1884
- method: "POST",
1885
- body: {
1886
- ...params,
1887
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1888
- },
1889
- stream: true
1890
- });
1891
- if (!response.ok) {
1892
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1893
- }
1894
- if (!response.body) {
1895
- throw new Error("Response body is null");
1896
- }
1897
- for await (const record of this.streamProcessor(response.body)) {
1898
- if (typeof record === "string") {
1899
- onRecord(JSON.parse(record));
1900
- } else {
1901
- onRecord(record);
1902
- }
1903
- }
1904
- }
1905
- };
1906
-
1907
2747
  // src/client.ts
1908
2748
  var MastraClient = class extends BaseResource {
2749
+ observability;
1909
2750
  constructor(options) {
1910
2751
  super(options);
2752
+ this.observability = new Observability(options);
1911
2753
  }
1912
2754
  /**
1913
2755
  * Retrieves all available agents
2756
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1914
2757
  * @returns Promise containing map of agent IDs to agent details
1915
2758
  */
1916
- getAgents() {
1917
- return this.request("/api/agents");
1918
- }
1919
- async getAGUI({ resourceId }) {
1920
- const agents = await this.getAgents();
1921
- return Object.entries(agents).reduce(
1922
- (acc, [agentId]) => {
1923
- const agent = this.getAgent(agentId);
1924
- acc[agentId] = new AGUIAdapter({
1925
- agentId,
1926
- agent,
1927
- resourceId
1928
- });
1929
- return acc;
1930
- },
1931
- {}
1932
- );
2759
+ getAgents(runtimeContext) {
2760
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2761
+ const searchParams = new URLSearchParams();
2762
+ if (runtimeContextParam) {
2763
+ searchParams.set("runtimeContext", runtimeContextParam);
2764
+ }
2765
+ const queryString = searchParams.toString();
2766
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
1933
2767
  }
1934
2768
  /**
1935
2769
  * Gets an agent instance by ID
@@ -1947,6 +2781,14 @@ var MastraClient = class extends BaseResource {
1947
2781
  getMemoryThreads(params) {
1948
2782
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1949
2783
  }
2784
+ /**
2785
+ * Retrieves memory config for a resource
2786
+ * @param params - Parameters containing the resource ID
2787
+ * @returns Promise containing array of memory threads
2788
+ */
2789
+ getMemoryConfig(params) {
2790
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2791
+ }
1950
2792
  /**
1951
2793
  * Creates a new memory thread
1952
2794
  * @param params - Parameters for creating the memory thread
@@ -1963,6 +2805,24 @@ var MastraClient = class extends BaseResource {
1963
2805
  getMemoryThread(threadId, agentId) {
1964
2806
  return new MemoryThread(this.options, threadId, agentId);
1965
2807
  }
2808
+ getThreadMessages(threadId, opts = {}) {
2809
+ let url = "";
2810
+ if (opts.agentId) {
2811
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2812
+ } else if (opts.networkId) {
2813
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2814
+ }
2815
+ return this.request(url);
2816
+ }
2817
+ deleteThread(threadId, opts = {}) {
2818
+ let url = "";
2819
+ if (opts.agentId) {
2820
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2821
+ } else if (opts.networkId) {
2822
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2823
+ }
2824
+ return this.request(url, { method: "DELETE" });
2825
+ }
1966
2826
  /**
1967
2827
  * Saves messages to memory
1968
2828
  * @param params - Parameters containing messages to save
@@ -2025,10 +2885,17 @@ var MastraClient = class extends BaseResource {
2025
2885
  }
2026
2886
  /**
2027
2887
  * Retrieves all available tools
2888
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2028
2889
  * @returns Promise containing map of tool IDs to tool details
2029
2890
  */
2030
- getTools() {
2031
- return this.request("/api/tools");
2891
+ getTools(runtimeContext) {
2892
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2893
+ const searchParams = new URLSearchParams();
2894
+ if (runtimeContextParam) {
2895
+ searchParams.set("runtimeContext", runtimeContextParam);
2896
+ }
2897
+ const queryString = searchParams.toString();
2898
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
2032
2899
  }
2033
2900
  /**
2034
2901
  * Gets a tool instance by ID
@@ -2036,29 +2903,21 @@ var MastraClient = class extends BaseResource {
2036
2903
  * @returns Tool instance
2037
2904
  */
2038
2905
  getTool(toolId) {
2039
- return new Tool2(this.options, toolId);
2040
- }
2041
- /**
2042
- * Retrieves all available legacy workflows
2043
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2044
- */
2045
- getLegacyWorkflows() {
2046
- return this.request("/api/workflows/legacy");
2047
- }
2048
- /**
2049
- * Gets a legacy workflow instance by ID
2050
- * @param workflowId - ID of the legacy workflow to retrieve
2051
- * @returns Legacy Workflow instance
2052
- */
2053
- getLegacyWorkflow(workflowId) {
2054
- return new LegacyWorkflow(this.options, workflowId);
2906
+ return new Tool(this.options, toolId);
2055
2907
  }
2056
2908
  /**
2057
2909
  * Retrieves all available workflows
2910
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2058
2911
  * @returns Promise containing map of workflow IDs to workflow details
2059
2912
  */
2060
- getWorkflows() {
2061
- return this.request("/api/workflows");
2913
+ getWorkflows(runtimeContext) {
2914
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2915
+ const searchParams = new URLSearchParams();
2916
+ if (runtimeContextParam) {
2917
+ searchParams.set("runtimeContext", runtimeContextParam);
2918
+ }
2919
+ const queryString = searchParams.toString();
2920
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
2062
2921
  }
2063
2922
  /**
2064
2923
  * Gets a workflow instance by ID
@@ -2068,6 +2927,20 @@ var MastraClient = class extends BaseResource {
2068
2927
  getWorkflow(workflowId) {
2069
2928
  return new Workflow(this.options, workflowId);
2070
2929
  }
2930
+ /**
2931
+ * Gets all available agent builder actions
2932
+ * @returns Promise containing map of action IDs to action details
2933
+ */
2934
+ getAgentBuilderActions() {
2935
+ return this.request("/api/agent-builder/");
2936
+ }
2937
+ /**
2938
+ * Gets an agent builder instance for executing agent-builder workflows
2939
+ * @returns AgentBuilder instance
2940
+ */
2941
+ getAgentBuilderAction(actionId) {
2942
+ return new AgentBuilder(this.options, actionId);
2943
+ }
2071
2944
  /**
2072
2945
  * Gets a vector instance by name
2073
2946
  * @param vectorName - Name of the vector to retrieve
@@ -2212,36 +3085,6 @@ var MastraClient = class extends BaseResource {
2212
3085
  return this.request(`/api/telemetry`);
2213
3086
  }
2214
3087
  }
2215
- /**
2216
- * Retrieves all available networks
2217
- * @returns Promise containing map of network IDs to network details
2218
- */
2219
- getNetworks() {
2220
- return this.request("/api/networks");
2221
- }
2222
- /**
2223
- * Retrieves all available vNext networks
2224
- * @returns Promise containing map of vNext network IDs to vNext network details
2225
- */
2226
- getVNextNetworks() {
2227
- return this.request("/api/networks/v-next");
2228
- }
2229
- /**
2230
- * Gets a network instance by ID
2231
- * @param networkId - ID of the network to retrieve
2232
- * @returns Network instance
2233
- */
2234
- getNetwork(networkId) {
2235
- return new Network(this.options, networkId);
2236
- }
2237
- /**
2238
- * Gets a vNext network instance by ID
2239
- * @param networkId - ID of the vNext network to retrieve
2240
- * @returns vNext Network instance
2241
- */
2242
- getVNextNetwork(networkId) {
2243
- return new VNextNetwork(this.options, networkId);
2244
- }
2245
3088
  /**
2246
3089
  * Retrieves a list of available MCP servers.
2247
3090
  * @param params - Optional parameters for pagination (limit, offset).
@@ -2346,7 +3189,7 @@ var MastraClient = class extends BaseResource {
2346
3189
  * @returns Promise containing the scorer
2347
3190
  */
2348
3191
  getScorer(scorerId) {
2349
- return this.request(`/api/scores/scorers/${scorerId}`);
3192
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
2350
3193
  }
2351
3194
  getScoresByScorerId(params) {
2352
3195
  const { page, perPage, scorerId, entityId, entityType } = params;
@@ -2364,7 +3207,7 @@ var MastraClient = class extends BaseResource {
2364
3207
  searchParams.set("perPage", String(perPage));
2365
3208
  }
2366
3209
  const queryString = searchParams.toString();
2367
- return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3210
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
2368
3211
  }
2369
3212
  /**
2370
3213
  * Retrieves scores by run ID
@@ -2381,7 +3224,7 @@ var MastraClient = class extends BaseResource {
2381
3224
  searchParams.set("perPage", String(perPage));
2382
3225
  }
2383
3226
  const queryString = searchParams.toString();
2384
- return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3227
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
2385
3228
  }
2386
3229
  /**
2387
3230
  * Retrieves scores by entity ID and type
@@ -2398,7 +3241,9 @@ var MastraClient = class extends BaseResource {
2398
3241
  searchParams.set("perPage", String(perPage));
2399
3242
  }
2400
3243
  const queryString = searchParams.toString();
2401
- return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3244
+ return this.request(
3245
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3246
+ );
2402
3247
  }
2403
3248
  /**
2404
3249
  * Saves a score
@@ -2411,8 +3256,48 @@ var MastraClient = class extends BaseResource {
2411
3256
  body: params
2412
3257
  });
2413
3258
  }
3259
+ /**
3260
+ * Retrieves model providers with available keys
3261
+ * @returns Promise containing model providers with available keys
3262
+ */
3263
+ getModelProviders() {
3264
+ return this.request(`/api/model-providers`);
3265
+ }
3266
+ getAITrace(traceId) {
3267
+ return this.observability.getTrace(traceId);
3268
+ }
3269
+ getAITraces(params) {
3270
+ return this.observability.getTraces(params);
3271
+ }
3272
+ getScoresBySpan(params) {
3273
+ return this.observability.getScoresBySpan(params);
3274
+ }
3275
+ score(params) {
3276
+ return this.observability.score(params);
3277
+ }
2414
3278
  };
2415
3279
 
3280
+ // src/tools.ts
3281
+ var ClientTool = class {
3282
+ id;
3283
+ description;
3284
+ inputSchema;
3285
+ outputSchema;
3286
+ execute;
3287
+ constructor(opts) {
3288
+ this.id = opts.id;
3289
+ this.description = opts.description;
3290
+ this.inputSchema = opts.inputSchema;
3291
+ this.outputSchema = opts.outputSchema;
3292
+ this.execute = opts.execute;
3293
+ }
3294
+ };
3295
+ function createTool(opts) {
3296
+ return new ClientTool(opts);
3297
+ }
3298
+
3299
+ exports.ClientTool = ClientTool;
2416
3300
  exports.MastraClient = MastraClient;
3301
+ exports.createTool = createTool;
2417
3302
  //# sourceMappingURL=index.cjs.map
2418
3303
  //# sourceMappingURL=index.cjs.map