@mastra/client-js 0.0.0-tsconfig-compile-20250703214351 → 0.0.0-unified-sidebar-20251010130811

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 (78) hide show
  1. package/CHANGELOG.md +1400 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +6 -7
  4. package/dist/client.d.ts +278 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/example.d.ts +2 -0
  7. package/dist/example.d.ts.map +1 -0
  8. package/dist/index.cjs +1761 -674
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -1164
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +1759 -674
  13. package/dist/index.js.map +1 -0
  14. package/dist/resources/a2a.d.ts +41 -0
  15. package/dist/resources/a2a.d.ts.map +1 -0
  16. package/dist/resources/agent-builder.d.ts +160 -0
  17. package/dist/resources/agent-builder.d.ts.map +1 -0
  18. package/dist/resources/agent.d.ts +184 -0
  19. package/dist/resources/agent.d.ts.map +1 -0
  20. package/dist/resources/base.d.ts +13 -0
  21. package/dist/resources/base.d.ts.map +1 -0
  22. package/dist/resources/index.d.ts +11 -0
  23. package/dist/resources/index.d.ts.map +1 -0
  24. package/dist/resources/mcp-tool.d.ts +28 -0
  25. package/dist/resources/mcp-tool.d.ts.map +1 -0
  26. package/dist/resources/memory-thread.d.ts +53 -0
  27. package/dist/resources/memory-thread.d.ts.map +1 -0
  28. package/dist/resources/network-memory-thread.d.ts +47 -0
  29. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  30. package/dist/resources/observability.d.ts +35 -0
  31. package/dist/resources/observability.d.ts.map +1 -0
  32. package/dist/resources/tool.d.ts +24 -0
  33. package/dist/resources/tool.d.ts.map +1 -0
  34. package/dist/resources/vector.d.ts +51 -0
  35. package/dist/resources/vector.d.ts.map +1 -0
  36. package/dist/resources/workflow.d.ts +269 -0
  37. package/dist/resources/workflow.d.ts.map +1 -0
  38. package/dist/tools.d.ts +22 -0
  39. package/dist/tools.d.ts.map +1 -0
  40. package/dist/types.d.ts +479 -0
  41. package/dist/types.d.ts.map +1 -0
  42. package/dist/utils/index.d.ts +5 -0
  43. package/dist/utils/index.d.ts.map +1 -0
  44. package/dist/utils/process-client-tools.d.ts +3 -0
  45. package/dist/utils/process-client-tools.d.ts.map +1 -0
  46. package/dist/utils/process-mastra-stream.d.ts +11 -0
  47. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  48. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  49. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  50. package/package.json +27 -15
  51. package/.turbo/turbo-build.log +0 -19
  52. package/dist/index.d.cts +0 -1164
  53. package/eslint.config.js +0 -6
  54. package/src/adapters/agui.test.ts +0 -180
  55. package/src/adapters/agui.ts +0 -239
  56. package/src/client.ts +0 -480
  57. package/src/example.ts +0 -67
  58. package/src/index.test.ts +0 -830
  59. package/src/index.ts +0 -2
  60. package/src/resources/a2a.ts +0 -88
  61. package/src/resources/agent.ts +0 -763
  62. package/src/resources/base.ts +0 -71
  63. package/src/resources/index.ts +0 -10
  64. package/src/resources/legacy-workflow.ts +0 -242
  65. package/src/resources/mcp-tool.ts +0 -48
  66. package/src/resources/memory-thread.ts +0 -63
  67. package/src/resources/network-memory-thread.ts +0 -63
  68. package/src/resources/network.ts +0 -85
  69. package/src/resources/tool.ts +0 -45
  70. package/src/resources/vNextNetwork.ts +0 -177
  71. package/src/resources/vector.ts +0 -83
  72. package/src/resources/workflow.ts +0 -396
  73. package/src/types.ts +0 -422
  74. package/src/utils/index.ts +0 -11
  75. package/src/utils/process-client-tools.ts +0 -32
  76. package/src/utils/zod-to-json-schema.ts +0 -10
  77. package/tsconfig.json +0 -5
  78. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,215 +1,62 @@
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');
4
+ var uuid = require('@lukeed/uuid');
5
+ var runtimeContext = require('@mastra/core/runtime-context');
6
+ var isVercelTool = require('@mastra/core/tools/is-vercel-tool');
6
7
  var zod = require('zod');
7
8
  var originalZodToJsonSchema = require('zod-to-json-schema');
8
- var tools = require('@mastra/core/tools');
9
- var runtimeContext = require('@mastra/core/runtime-context');
10
9
 
11
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
11
 
13
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
14
13
 
15
- // src/adapters/agui.ts
16
- var AGUIAdapter = class extends client.AbstractAgent {
17
- agent;
18
- resourceId;
19
- constructor({ agent, agentId, resourceId, ...rest }) {
20
- super({
21
- agentId,
22
- ...rest
23
- });
24
- this.agent = agent;
25
- this.resourceId = resourceId;
26
- }
27
- run(input) {
28
- return new rxjs.Observable((subscriber) => {
29
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
30
- subscriber.next({
31
- type: client.EventType.RUN_STARTED,
32
- threadId: input.threadId,
33
- runId: input.runId
34
- });
35
- this.agent.stream({
36
- threadId: input.threadId,
37
- resourceId: this.resourceId ?? "",
38
- runId: input.runId,
39
- messages: convertedMessages,
40
- clientTools: input.tools.reduce(
41
- (acc, tool) => {
42
- acc[tool.name] = {
43
- id: tool.name,
44
- description: tool.description,
45
- inputSchema: tool.parameters
46
- };
47
- return acc;
48
- },
49
- {}
50
- )
51
- }).then((response) => {
52
- let currentMessageId = void 0;
53
- let isInTextMessage = false;
54
- return response.processDataStream({
55
- onTextPart: (text) => {
56
- if (currentMessageId === void 0) {
57
- currentMessageId = generateUUID();
58
- const message2 = {
59
- type: client.EventType.TEXT_MESSAGE_START,
60
- messageId: currentMessageId,
61
- role: "assistant"
62
- };
63
- subscriber.next(message2);
64
- isInTextMessage = true;
65
- }
66
- const message = {
67
- type: client.EventType.TEXT_MESSAGE_CONTENT,
68
- messageId: currentMessageId,
69
- delta: text
70
- };
71
- subscriber.next(message);
72
- },
73
- onFinishMessagePart: () => {
74
- if (currentMessageId !== void 0) {
75
- const message = {
76
- type: client.EventType.TEXT_MESSAGE_END,
77
- messageId: currentMessageId
78
- };
79
- subscriber.next(message);
80
- isInTextMessage = false;
81
- }
82
- subscriber.next({
83
- type: client.EventType.RUN_FINISHED,
84
- threadId: input.threadId,
85
- runId: input.runId
86
- });
87
- subscriber.complete();
88
- },
89
- onToolCallPart(streamPart) {
90
- const parentMessageId = currentMessageId || generateUUID();
91
- if (isInTextMessage) {
92
- const message = {
93
- type: client.EventType.TEXT_MESSAGE_END,
94
- messageId: parentMessageId
95
- };
96
- subscriber.next(message);
97
- isInTextMessage = false;
98
- }
99
- subscriber.next({
100
- type: client.EventType.TOOL_CALL_START,
101
- toolCallId: streamPart.toolCallId,
102
- toolCallName: streamPart.toolName,
103
- parentMessageId
104
- });
105
- subscriber.next({
106
- type: client.EventType.TOOL_CALL_ARGS,
107
- toolCallId: streamPart.toolCallId,
108
- delta: JSON.stringify(streamPart.args),
109
- parentMessageId
110
- });
111
- subscriber.next({
112
- type: client.EventType.TOOL_CALL_END,
113
- toolCallId: streamPart.toolCallId,
114
- parentMessageId
115
- });
116
- }
117
- });
118
- }).catch((error) => {
119
- console.error("error", error);
120
- subscriber.error(error);
121
- });
122
- return () => {
123
- };
124
- });
125
- }
126
- };
127
- function generateUUID() {
128
- if (typeof crypto !== "undefined") {
129
- if (typeof crypto.randomUUID === "function") {
130
- return crypto.randomUUID();
131
- }
132
- if (typeof crypto.getRandomValues === "function") {
133
- const buffer = new Uint8Array(16);
134
- crypto.getRandomValues(buffer);
135
- buffer[6] = buffer[6] & 15 | 64;
136
- buffer[8] = buffer[8] & 63 | 128;
137
- let hex = "";
138
- for (let i = 0; i < 16; i++) {
139
- hex += buffer[i].toString(16).padStart(2, "0");
140
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
141
- }
142
- 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());
143
19
  }
20
+ return runtimeContext$1;
144
21
  }
145
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
146
- const r = Math.random() * 16 | 0;
147
- const v = c === "x" ? r : r & 3 | 8;
148
- return v.toString(16);
149
- });
22
+ return void 0;
150
23
  }
151
- function convertMessagesToMastraMessages(messages) {
152
- const result = [];
153
- for (const message of messages) {
154
- if (message.role === "assistant") {
155
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
156
- for (const toolCall of message.toolCalls ?? []) {
157
- parts.push({
158
- type: "tool-call",
159
- toolCallId: toolCall.id,
160
- toolName: toolCall.function.name,
161
- args: JSON.parse(toolCall.function.arguments)
162
- });
163
- }
164
- result.push({
165
- role: "assistant",
166
- content: parts
167
- });
168
- if (message.toolCalls?.length) {
169
- result.push({
170
- role: "tool",
171
- content: message.toolCalls.map((toolCall) => ({
172
- type: "tool-result",
173
- toolCallId: toolCall.id,
174
- toolName: toolCall.function.name,
175
- result: JSON.parse(toolCall.function.arguments)
176
- }))
177
- });
178
- }
179
- } else if (message.role === "user") {
180
- result.push({
181
- role: "user",
182
- content: message.content || ""
183
- });
184
- } else if (message.role === "tool") {
185
- result.push({
186
- role: "tool",
187
- content: [
188
- {
189
- type: "tool-result",
190
- toolCallId: message.toolCallId,
191
- toolName: "unknown",
192
- result: message.content
193
- }
194
- ]
195
- });
196
- }
24
+ function base64RuntimeContext(runtimeContext) {
25
+ if (runtimeContext) {
26
+ return btoa(JSON.stringify(runtimeContext));
197
27
  }
198
- 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";
199
40
  }
200
41
  function zodToJsonSchema(zodSchema) {
201
- if (!(zodSchema instanceof zod.ZodSchema)) {
42
+ if (!isZodType(zodSchema)) {
202
43
  return zodSchema;
203
44
  }
204
- 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" });
205
50
  }
51
+
52
+ // src/utils/process-client-tools.ts
206
53
  function processClientTools(clientTools) {
207
54
  if (!clientTools) {
208
55
  return void 0;
209
56
  }
210
57
  return Object.fromEntries(
211
58
  Object.entries(clientTools).map(([key, value]) => {
212
- if (tools.isVercelTool(value)) {
59
+ if (isVercelTool.isVercelTool(value)) {
213
60
  return [
214
61
  key,
215
62
  {
@@ -231,6 +78,60 @@ function processClientTools(clientTools) {
231
78
  );
232
79
  }
233
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
+
234
135
  // src/resources/base.ts
235
136
  var BaseResource = class {
236
137
  options;
@@ -245,19 +146,21 @@ var BaseResource = class {
245
146
  */
246
147
  async request(path, options = {}) {
247
148
  let lastError = null;
248
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
149
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
249
150
  let delay = backoffMs;
250
151
  for (let attempt = 0; attempt <= retries; attempt++) {
251
152
  try {
252
153
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
253
154
  ...options,
254
155
  headers: {
255
- ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
156
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
256
157
  ...headers,
257
158
  ...options.headers
258
159
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
259
160
  // 'x-mastra-client-type': 'js',
260
161
  },
162
+ signal: this.options.abortSignal,
163
+ credentials: options.credentials ?? credentials,
261
164
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
262
165
  });
263
166
  if (!response.ok) {
@@ -290,14 +193,62 @@ var BaseResource = class {
290
193
  throw lastError || new Error("Request failed");
291
194
  }
292
195
  };
293
- function parseClientRuntimeContext(runtimeContext$1) {
294
- if (runtimeContext$1) {
295
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
296
- 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
+ }
297
250
  }
298
- return runtimeContext$1;
299
251
  }
300
- return void 0;
301
252
  }
302
253
  var AgentVoice = class extends BaseResource {
303
254
  constructor(options, agentId) {
@@ -340,17 +291,21 @@ var AgentVoice = class extends BaseResource {
340
291
  }
341
292
  /**
342
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
343
296
  * @returns Promise containing list of available speakers
344
297
  */
345
- getSpeakers() {
346
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
298
+ getSpeakers(runtimeContext) {
299
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
347
300
  }
348
301
  /**
349
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
350
305
  * @returns Promise containing a check if the agent has listening capabilities
351
306
  */
352
- getListener() {
353
- return this.request(`/api/agents/${this.agentId}/voice/listener`);
307
+ getListener(runtimeContext) {
308
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
354
309
  }
355
310
  };
356
311
  var Agent = class extends BaseResource {
@@ -362,12 +317,13 @@ var Agent = class extends BaseResource {
362
317
  voice;
363
318
  /**
364
319
  * Retrieves details about the agent
320
+ * @param runtimeContext - Optional runtime context to pass as query parameter
365
321
  * @returns Promise containing agent details including model and instructions
366
322
  */
367
- details() {
368
- return this.request(`/api/agents/${this.agentId}`);
323
+ details(runtimeContext) {
324
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
369
325
  }
370
- async generate(params) {
326
+ async generateLegacy(params) {
371
327
  const processedParams = {
372
328
  ...params,
373
329
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -376,26 +332,38 @@ var Agent = class extends BaseResource {
376
332
  clientTools: processClientTools(params.clientTools)
377
333
  };
378
334
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
379
- const response = await this.request(`/api/agents/${this.agentId}/generate`, {
380
- method: "POST",
381
- body: processedParams
382
- });
335
+ const response = await this.request(
336
+ `/api/agents/${this.agentId}/generate-legacy`,
337
+ {
338
+ method: "POST",
339
+ body: processedParams
340
+ }
341
+ );
383
342
  if (response.finishReason === "tool-calls") {
384
- for (const toolCall of response.toolCalls) {
343
+ const toolCalls = response.toolCalls;
344
+ if (!toolCalls || !Array.isArray(toolCalls)) {
345
+ return response;
346
+ }
347
+ for (const toolCall of toolCalls) {
385
348
  const clientTool = params.clientTools?.[toolCall.toolName];
386
349
  if (clientTool && clientTool.execute) {
387
350
  const result = await clientTool.execute(
388
- { 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
+ },
389
361
  {
390
362
  messages: response.messages,
391
363
  toolCallId: toolCall?.toolCallId
392
364
  }
393
365
  );
394
366
  const updatedMessages = [
395
- {
396
- role: "user",
397
- content: params.messages
398
- },
399
367
  ...response.response.messages,
400
368
  {
401
369
  role: "tool",
@@ -418,6 +386,47 @@ var Agent = class extends BaseResource {
418
386
  }
419
387
  return response;
420
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
+ }
421
430
  async processChatResponse({
422
431
  stream,
423
432
  update,
@@ -432,7 +441,7 @@ var Agent = class extends BaseResource {
432
441
  return Math.max(max, toolInvocation.step ?? 0);
433
442
  }, 0) ?? 0) : 0;
434
443
  const message = replaceLastMessage ? structuredClone(lastMessage) : {
435
- id: crypto.randomUUID(),
444
+ id: uuid.v4(),
436
445
  createdAt: getCurrentDate(),
437
446
  role: "assistant",
438
447
  content: "",
@@ -477,7 +486,7 @@ var Agent = class extends BaseResource {
477
486
  // changes. This is why we need to add a revision id to ensure that the message
478
487
  // is updated with SWR (without it, the changes get stuck in SWR and are not
479
488
  // forwarded to rendering):
480
- revisionId: crypto.randomUUID()
489
+ revisionId: uuid.v4()
481
490
  };
482
491
  update({
483
492
  message: copiedMessage,
@@ -685,7 +694,7 @@ var Agent = class extends BaseResource {
685
694
  * @param params - Stream parameters including prompt
686
695
  * @returns Promise containing the enhanced Response object with processDataStream method
687
696
  */
688
- async stream(params) {
697
+ async streamLegacy(params) {
689
698
  const processedParams = {
690
699
  ...params,
691
700
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -694,7 +703,7 @@ var Agent = class extends BaseResource {
694
703
  clientTools: processClientTools(params.clientTools)
695
704
  };
696
705
  const { readable, writable } = new TransformStream();
697
- const response = await this.processStreamResponse(processedParams, writable);
706
+ const response = await this.processStreamResponseLegacy(processedParams, writable);
698
707
  const streamResponse = new Response(readable, {
699
708
  status: response.status,
700
709
  statusText: response.statusText,
@@ -708,9 +717,267 @@ var Agent = class extends BaseResource {
708
717
  };
709
718
  return streamResponse;
710
719
  }
711
- /**
712
- * Processes the stream response and handles tool calls
713
- */
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
+ }
714
981
  async processStreamResponse(processedParams, writable) {
715
982
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
716
983
  method: "POST",
@@ -724,15 +991,38 @@ var Agent = class extends BaseResource {
724
991
  let toolCalls = [];
725
992
  let messages = [];
726
993
  const [streamForWritable, streamForProcessing] = response.body.tee();
727
- streamForWritable.pipeTo(writable, {
728
- preventClose: true
729
- }).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) => {
730
1015
  console.error("Error piping to writable stream:", error);
731
1016
  });
732
- this.processChatResponse({
1017
+ this.processChatResponse_vNext({
733
1018
  stream: streamForProcessing,
734
1019
  update: ({ message }) => {
735
- messages.push(message);
1020
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1021
+ if (existingIndex !== -1) {
1022
+ messages[existingIndex] = message;
1023
+ } else {
1024
+ messages.push(message);
1025
+ }
736
1026
  },
737
1027
  onFinish: async ({ finishReason, message }) => {
738
1028
  if (finishReason === "tool-calls") {
@@ -740,23 +1030,30 @@ var Agent = class extends BaseResource {
740
1030
  if (toolCall) {
741
1031
  toolCalls.push(toolCall);
742
1032
  }
1033
+ let shouldExecuteClientTool = false;
743
1034
  for (const toolCall2 of toolCalls) {
744
1035
  const clientTool = processedParams.clientTools?.[toolCall2.toolName];
745
1036
  if (clientTool && clientTool.execute) {
1037
+ shouldExecuteClientTool = true;
746
1038
  const result = await clientTool.execute(
747
1039
  {
748
1040
  context: toolCall2?.args,
749
1041
  runId: processedParams.runId,
750
1042
  resourceId: processedParams.resourceId,
751
1043
  threadId: processedParams.threadId,
752
- 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
+ }
753
1049
  },
754
1050
  {
755
1051
  messages: response.messages,
756
1052
  toolCallId: toolCall2?.toolCallId
757
1053
  }
758
1054
  );
759
- 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;
760
1057
  const toolInvocationPart = lastMessage?.parts?.find(
761
1058
  (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
762
1059
  );
@@ -774,8 +1071,176 @@ var Agent = class extends BaseResource {
774
1071
  toolInvocation.state = "result";
775
1072
  toolInvocation.result = result;
776
1073
  }
777
- const writer = writable.getWriter();
778
- try {
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 {
779
1244
  await writer.write(
780
1245
  new TextEncoder().encode(
781
1246
  "a:" + JSON.stringify({
@@ -787,15 +1252,15 @@ var Agent = class extends BaseResource {
787
1252
  } finally {
788
1253
  writer.releaseLock();
789
1254
  }
790
- const originalMessages = processedParams.messages;
791
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
792
- this.processStreamResponse(
1255
+ this.processStreamResponseLegacy(
793
1256
  {
794
1257
  ...processedParams,
795
- messages: [...messageArray, ...messages, lastMessage]
1258
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
796
1259
  },
797
1260
  writable
798
- );
1261
+ ).catch((error) => {
1262
+ console.error("Error processing stream response:", error);
1263
+ });
799
1264
  }
800
1265
  }
801
1266
  } else {
@@ -805,6 +1270,8 @@ var Agent = class extends BaseResource {
805
1270
  }
806
1271
  },
807
1272
  lastMessage: void 0
1273
+ }).catch((error) => {
1274
+ console.error("Error processing stream response:", error);
808
1275
  });
809
1276
  } catch (error) {
810
1277
  console.error("Error processing stream response:", error);
@@ -814,10 +1281,11 @@ var Agent = class extends BaseResource {
814
1281
  /**
815
1282
  * Gets details about a specific tool available to the agent
816
1283
  * @param toolId - ID of the tool to retrieve
1284
+ * @param runtimeContext - Optional runtime context to pass as query parameter
817
1285
  * @returns Promise containing tool details
818
1286
  */
819
- getTool(toolId) {
820
- 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)}`);
821
1289
  }
822
1290
  /**
823
1291
  * Executes a tool for the agent
@@ -828,7 +1296,7 @@ var Agent = class extends BaseResource {
828
1296
  executeTool(toolId, params) {
829
1297
  const body = {
830
1298
  data: params.data,
831
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1299
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
832
1300
  };
833
1301
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
834
1302
  method: "POST",
@@ -837,73 +1305,58 @@ var Agent = class extends BaseResource {
837
1305
  }
838
1306
  /**
839
1307
  * Retrieves evaluation results for the agent
1308
+ * @param runtimeContext - Optional runtime context to pass as query parameter
840
1309
  * @returns Promise containing agent evaluations
841
1310
  */
842
- evals() {
843
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1311
+ evals(runtimeContext) {
1312
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
844
1313
  }
845
1314
  /**
846
1315
  * Retrieves live evaluation results for the agent
1316
+ * @param runtimeContext - Optional runtime context to pass as query parameter
847
1317
  * @returns Promise containing live agent evaluations
848
1318
  */
849
- liveEvals() {
850
- return this.request(`/api/agents/${this.agentId}/evals/live`);
851
- }
852
- };
853
- var Network = class extends BaseResource {
854
- constructor(options, networkId) {
855
- super(options);
856
- this.networkId = networkId;
1319
+ liveEvals(runtimeContext) {
1320
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
857
1321
  }
858
1322
  /**
859
- * Retrieves details about the network
860
- * @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
861
1326
  */
862
- details() {
863
- 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
+ });
864
1332
  }
865
1333
  /**
866
- * Generates a response from the agent
867
- * @param params - Generation parameters including prompt
868
- * @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
869
1337
  */
870
- generate(params) {
871
- const processedParams = {
872
- ...params,
873
- output: zodToJsonSchema(params.output),
874
- experimental_output: zodToJsonSchema(params.experimental_output)
875
- };
876
- return this.request(`/api/networks/${this.networkId}/generate`, {
1338
+ updateModelInModelList({ modelConfigId, ...params }) {
1339
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
877
1340
  method: "POST",
878
- body: processedParams
1341
+ body: params
879
1342
  });
880
1343
  }
881
1344
  /**
882
- * Streams a response from the agent
883
- * @param params - Stream parameters including prompt
884
- * @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
885
1348
  */
886
- async stream(params) {
887
- const processedParams = {
888
- ...params,
889
- output: zodToJsonSchema(params.output),
890
- experimental_output: zodToJsonSchema(params.experimental_output)
891
- };
892
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
1349
+ reorderModelList(params) {
1350
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
893
1351
  method: "POST",
894
- body: processedParams,
895
- stream: true
1352
+ body: params
896
1353
  });
897
- if (!response.body) {
898
- throw new Error("No response body");
899
- }
900
- response.processDataStream = async (options = {}) => {
901
- await uiUtils.processDataStream({
902
- stream: response.body,
903
- ...options
904
- });
905
- };
906
- 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.");
907
1360
  }
908
1361
  };
909
1362
 
@@ -953,6 +1406,36 @@ var MemoryThread = class extends BaseResource {
953
1406
  });
954
1407
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
955
1408
  }
1409
+ /**
1410
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1411
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1412
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1413
+ */
1414
+ getMessagesPaginated({
1415
+ selectBy,
1416
+ ...rest
1417
+ }) {
1418
+ const query = new URLSearchParams({
1419
+ ...rest,
1420
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1421
+ });
1422
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1423
+ }
1424
+ /**
1425
+ * Deletes one or more messages from the thread
1426
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1427
+ * message object with id property, or array of message objects
1428
+ * @returns Promise containing deletion result
1429
+ */
1430
+ deleteMessages(messageIds) {
1431
+ const query = new URLSearchParams({
1432
+ agentId: this.agentId
1433
+ });
1434
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1435
+ method: "POST",
1436
+ body: { messageIds }
1437
+ });
1438
+ }
956
1439
  };
957
1440
 
958
1441
  // src/resources/vector.ts
@@ -964,10 +1447,13 @@ var Vector = class extends BaseResource {
964
1447
  /**
965
1448
  * Retrieves details about a specific vector index
966
1449
  * @param indexName - Name of the index to get details for
1450
+ * @param runtimeContext - Optional runtime context to pass as query parameter
967
1451
  * @returns Promise containing vector index details
968
1452
  */
969
- details(indexName) {
970
- 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
+ );
971
1457
  }
972
1458
  /**
973
1459
  * Deletes a vector index
@@ -981,10 +1467,11 @@ var Vector = class extends BaseResource {
981
1467
  }
982
1468
  /**
983
1469
  * Retrieves a list of all available indexes
1470
+ * @param runtimeContext - Optional runtime context to pass as query parameter
984
1471
  * @returns Promise containing array of index names
985
1472
  */
986
- getIndexes() {
987
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1473
+ getIndexes(runtimeContext) {
1474
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
988
1475
  }
989
1476
  /**
990
1477
  * Creates a new vector index
@@ -1021,199 +1508,19 @@ var Vector = class extends BaseResource {
1021
1508
  }
1022
1509
  };
1023
1510
 
1024
- // src/resources/legacy-workflow.ts
1025
- var RECORD_SEPARATOR = "";
1026
- var LegacyWorkflow = class extends BaseResource {
1027
- constructor(options, workflowId) {
1028
- super(options);
1029
- this.workflowId = workflowId;
1030
- }
1031
- /**
1032
- * Retrieves details about the legacy workflow
1033
- * @returns Promise containing legacy workflow details including steps and graphs
1034
- */
1035
- details() {
1036
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1037
- }
1038
- /**
1039
- * Retrieves all runs for a legacy workflow
1040
- * @param params - Parameters for filtering runs
1041
- * @returns Promise containing legacy workflow runs array
1042
- */
1043
- runs(params) {
1044
- const searchParams = new URLSearchParams();
1045
- if (params?.fromDate) {
1046
- searchParams.set("fromDate", params.fromDate.toISOString());
1047
- }
1048
- if (params?.toDate) {
1049
- searchParams.set("toDate", params.toDate.toISOString());
1050
- }
1051
- if (params?.limit) {
1052
- searchParams.set("limit", String(params.limit));
1053
- }
1054
- if (params?.offset) {
1055
- searchParams.set("offset", String(params.offset));
1056
- }
1057
- if (params?.resourceId) {
1058
- searchParams.set("resourceId", params.resourceId);
1059
- }
1060
- if (searchParams.size) {
1061
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1062
- } else {
1063
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1064
- }
1065
- }
1066
- /**
1067
- * Creates a new legacy workflow run
1068
- * @returns Promise containing the generated run ID
1069
- */
1070
- createRun(params) {
1071
- const searchParams = new URLSearchParams();
1072
- if (!!params?.runId) {
1073
- searchParams.set("runId", params.runId);
1074
- }
1075
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
1076
- method: "POST"
1077
- });
1078
- }
1079
- /**
1080
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
1081
- * @param params - Object containing the runId and triggerData
1082
- * @returns Promise containing success message
1083
- */
1084
- start(params) {
1085
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1086
- method: "POST",
1087
- body: params?.triggerData
1088
- });
1089
- }
1090
- /**
1091
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
1092
- * @param stepId - ID of the step to resume
1093
- * @param runId - ID of the legacy workflow run
1094
- * @param context - Context to resume the legacy workflow with
1095
- * @returns Promise containing the legacy workflow resume results
1096
- */
1097
- resume({
1098
- stepId,
1099
- runId,
1100
- context
1101
- }) {
1102
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
1103
- method: "POST",
1104
- body: {
1105
- stepId,
1106
- context
1107
- }
1108
- });
1109
- }
1110
- /**
1111
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1112
- * @param params - Object containing the optional runId and triggerData
1113
- * @returns Promise containing the workflow execution results
1114
- */
1115
- startAsync(params) {
1116
- const searchParams = new URLSearchParams();
1117
- if (!!params?.runId) {
1118
- searchParams.set("runId", params.runId);
1119
- }
1120
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
1121
- method: "POST",
1122
- body: params?.triggerData
1123
- });
1124
- }
1125
- /**
1126
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
1127
- * @param params - Object containing the runId, stepId, and context
1128
- * @returns Promise containing the workflow resume results
1129
- */
1130
- resumeAsync(params) {
1131
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
1132
- method: "POST",
1133
- body: {
1134
- stepId: params.stepId,
1135
- context: params.context
1136
- }
1137
- });
1138
- }
1139
- /**
1140
- * Creates an async generator that processes a readable stream and yields records
1141
- * separated by the Record Separator character (\x1E)
1142
- *
1143
- * @param stream - The readable stream to process
1144
- * @returns An async generator that yields parsed records
1145
- */
1146
- async *streamProcessor(stream) {
1147
- const reader = stream.getReader();
1148
- let doneReading = false;
1149
- let buffer = "";
1150
- try {
1151
- while (!doneReading) {
1152
- const { done, value } = await reader.read();
1153
- doneReading = done;
1154
- if (done && !value) continue;
1155
- try {
1156
- const decoded = value ? new TextDecoder().decode(value) : "";
1157
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1158
- buffer = chunks.pop() || "";
1159
- for (const chunk of chunks) {
1160
- if (chunk) {
1161
- if (typeof chunk === "string") {
1162
- try {
1163
- const parsedChunk = JSON.parse(chunk);
1164
- yield parsedChunk;
1165
- } catch {
1166
- }
1167
- }
1168
- }
1169
- }
1170
- } catch {
1171
- }
1172
- }
1173
- if (buffer) {
1174
- try {
1175
- yield JSON.parse(buffer);
1176
- } catch {
1177
- }
1178
- }
1179
- } finally {
1180
- reader.cancel().catch(() => {
1181
- });
1182
- }
1183
- }
1184
- /**
1185
- * Watches legacy workflow transitions in real-time
1186
- * @param runId - Optional run ID to filter the watch stream
1187
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
1188
- */
1189
- async watch({ runId }, onRecord) {
1190
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
1191
- stream: true
1192
- });
1193
- if (!response.ok) {
1194
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
1195
- }
1196
- if (!response.body) {
1197
- throw new Error("Response body is null");
1198
- }
1199
- for await (const record of this.streamProcessor(response.body)) {
1200
- onRecord(record);
1201
- }
1202
- }
1203
- };
1204
-
1205
1511
  // src/resources/tool.ts
1206
- var Tool2 = class extends BaseResource {
1512
+ var Tool = class extends BaseResource {
1207
1513
  constructor(options, toolId) {
1208
1514
  super(options);
1209
1515
  this.toolId = toolId;
1210
1516
  }
1211
1517
  /**
1212
1518
  * Retrieves details about the tool
1519
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1213
1520
  * @returns Promise containing tool details including description and schemas
1214
1521
  */
1215
- details() {
1216
- return this.request(`/api/tools/${this.toolId}`);
1522
+ details(runtimeContext) {
1523
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1217
1524
  }
1218
1525
  /**
1219
1526
  * Executes the tool with the provided parameters
@@ -1237,7 +1544,7 @@ var Tool2 = class extends BaseResource {
1237
1544
  };
1238
1545
 
1239
1546
  // src/resources/workflow.ts
1240
- var RECORD_SEPARATOR2 = "";
1547
+ var RECORD_SEPARATOR = "";
1241
1548
  var Workflow = class extends BaseResource {
1242
1549
  constructor(options, workflowId) {
1243
1550
  super(options);
@@ -1261,7 +1568,7 @@ var Workflow = class extends BaseResource {
1261
1568
  if (done && !value) continue;
1262
1569
  try {
1263
1570
  const decoded = value ? new TextDecoder().decode(value) : "";
1264
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1571
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1265
1572
  buffer = chunks.pop() || "";
1266
1573
  for (const chunk of chunks) {
1267
1574
  if (chunk) {
@@ -1290,17 +1597,20 @@ var Workflow = class extends BaseResource {
1290
1597
  }
1291
1598
  /**
1292
1599
  * Retrieves details about the workflow
1600
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1293
1601
  * @returns Promise containing workflow details including steps and graphs
1294
1602
  */
1295
- details() {
1296
- return this.request(`/api/workflows/${this.workflowId}`);
1603
+ details(runtimeContext) {
1604
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1297
1605
  }
1298
1606
  /**
1299
1607
  * Retrieves all runs for a workflow
1300
1608
  * @param params - Parameters for filtering runs
1609
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1301
1610
  * @returns Promise containing workflow runs array
1302
1611
  */
1303
- runs(params) {
1612
+ runs(params, runtimeContext) {
1613
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1304
1614
  const searchParams = new URLSearchParams();
1305
1615
  if (params?.fromDate) {
1306
1616
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1317,6 +1627,9 @@ var Workflow = class extends BaseResource {
1317
1627
  if (params?.resourceId) {
1318
1628
  searchParams.set("resourceId", params.resourceId);
1319
1629
  }
1630
+ if (runtimeContextParam) {
1631
+ searchParams.set("runtimeContext", runtimeContextParam);
1632
+ }
1320
1633
  if (searchParams.size) {
1321
1634
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1322
1635
  } else {
@@ -1326,18 +1639,22 @@ var Workflow = class extends BaseResource {
1326
1639
  /**
1327
1640
  * Retrieves a specific workflow run by its ID
1328
1641
  * @param runId - The ID of the workflow run to retrieve
1642
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1329
1643
  * @returns Promise containing the workflow run details
1330
1644
  */
1331
- runById(runId) {
1332
- 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)}`);
1333
1647
  }
1334
1648
  /**
1335
1649
  * Retrieves the execution result for a specific workflow run by its ID
1336
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
1337
1652
  * @returns Promise containing the workflow run execution result
1338
1653
  */
1339
- runExecutionResult(runId) {
1340
- 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
+ );
1341
1658
  }
1342
1659
  /**
1343
1660
  * Cancels a specific workflow run by its ID
@@ -1360,19 +1677,83 @@ var Workflow = class extends BaseResource {
1360
1677
  body: { event: params.event, data: params.data }
1361
1678
  });
1362
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
+ }
1363
1689
  /**
1364
1690
  * Creates a new workflow run
1365
1691
  * @param params - Optional object containing the optional runId
1366
- * @returns Promise containing the runId of the created run
1692
+ * @returns Promise containing the runId of the created run with methods to control execution
1367
1693
  */
1368
- createRun(params) {
1694
+ async createRunAsync(params) {
1369
1695
  const searchParams = new URLSearchParams();
1370
1696
  if (!!params?.runId) {
1371
1697
  searchParams.set("runId", params.runId);
1372
1698
  }
1373
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1374
- method: "POST"
1375
- });
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
+ };
1376
1757
  }
1377
1758
  /**
1378
1759
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -1383,7 +1764,7 @@ var Workflow = class extends BaseResource {
1383
1764
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1384
1765
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1385
1766
  method: "POST",
1386
- body: { inputData: params?.inputData, runtimeContext }
1767
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1387
1768
  });
1388
1769
  }
1389
1770
  /**
@@ -1395,73 +1776,228 @@ var Workflow = class extends BaseResource {
1395
1776
  step,
1396
1777
  runId,
1397
1778
  resumeData,
1779
+ tracingOptions,
1398
1780
  ...rest
1399
1781
  }) {
1400
1782
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1401
1783
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1402
1784
  method: "POST",
1403
- stream: true,
1404
1785
  body: {
1405
1786
  step,
1406
1787
  resumeData,
1407
- runtimeContext
1788
+ runtimeContext,
1789
+ tracingOptions
1790
+ }
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1795
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1796
+ * @returns Promise containing the workflow execution results
1797
+ */
1798
+ startAsync(params) {
1799
+ const searchParams = new URLSearchParams();
1800
+ if (!!params?.runId) {
1801
+ searchParams.set("runId", params.runId);
1802
+ }
1803
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1804
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1805
+ method: "POST",
1806
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1807
+ });
1808
+ }
1809
+ /**
1810
+ * Starts a workflow run and returns a stream
1811
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1812
+ * @returns Promise containing the workflow execution results
1813
+ */
1814
+ async stream(params) {
1815
+ const searchParams = new URLSearchParams();
1816
+ if (!!params?.runId) {
1817
+ searchParams.set("runId", params.runId);
1818
+ }
1819
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1820
+ const response = await this.request(
1821
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1822
+ {
1823
+ method: "POST",
1824
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions },
1825
+ stream: true
1826
+ }
1827
+ );
1828
+ if (!response.ok) {
1829
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1830
+ }
1831
+ if (!response.body) {
1832
+ throw new Error("Response body is null");
1833
+ }
1834
+ let failedChunk = void 0;
1835
+ const transformStream = new TransformStream({
1836
+ start() {
1837
+ },
1838
+ async transform(chunk, controller) {
1839
+ try {
1840
+ const decoded = new TextDecoder().decode(chunk);
1841
+ const chunks = decoded.split(RECORD_SEPARATOR);
1842
+ for (const chunk2 of chunks) {
1843
+ if (chunk2) {
1844
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1845
+ try {
1846
+ const parsedChunk = JSON.parse(newChunk);
1847
+ controller.enqueue(parsedChunk);
1848
+ failedChunk = void 0;
1849
+ } catch {
1850
+ failedChunk = newChunk;
1851
+ }
1852
+ }
1853
+ }
1854
+ } catch {
1855
+ }
1856
+ }
1857
+ });
1858
+ return response.body.pipeThrough(transformStream);
1859
+ }
1860
+ /**
1861
+ * Observes workflow stream for a workflow run
1862
+ * @param params - Object containing the runId
1863
+ * @returns Promise containing the workflow execution results
1864
+ */
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
+ }
1408
1903
  }
1409
1904
  });
1905
+ return response.body.pipeThrough(transformStream);
1410
1906
  }
1411
1907
  /**
1412
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1908
+ * Starts a workflow run and returns a stream
1413
1909
  * @param params - Object containing the optional runId, inputData and runtimeContext
1414
1910
  * @returns Promise containing the workflow execution results
1415
1911
  */
1416
- startAsync(params) {
1912
+ async streamVNext(params) {
1417
1913
  const searchParams = new URLSearchParams();
1418
1914
  if (!!params?.runId) {
1419
1915
  searchParams.set("runId", params.runId);
1420
1916
  }
1421
1917
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1422
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1423
- method: "POST",
1424
- body: { inputData: params.inputData, 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
+ }
1425
1960
  });
1961
+ return response.body.pipeThrough(transformStream);
1426
1962
  }
1427
1963
  /**
1428
- * Starts a workflow run and returns a stream
1429
- * @param params - Object containing the optional runId, inputData and runtimeContext
1964
+ * Observes workflow vNext stream for a workflow run
1965
+ * @param params - Object containing the runId
1430
1966
  * @returns Promise containing the workflow execution results
1431
1967
  */
1432
- async stream(params) {
1968
+ async observeStreamVNext(params) {
1433
1969
  const searchParams = new URLSearchParams();
1434
- if (!!params?.runId) {
1435
- searchParams.set("runId", params.runId);
1436
- }
1437
- const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1970
+ searchParams.set("runId", params.runId);
1438
1971
  const response = await this.request(
1439
- `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1972
+ `/api/workflows/${this.workflowId}/observe-streamVNext?${searchParams.toString()}`,
1440
1973
  {
1441
1974
  method: "POST",
1442
- body: { inputData: params.inputData, runtimeContext },
1443
1975
  stream: true
1444
1976
  }
1445
1977
  );
1446
1978
  if (!response.ok) {
1447
- throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1979
+ throw new Error(`Failed to observe stream vNext workflow: ${response.statusText}`);
1448
1980
  }
1449
1981
  if (!response.body) {
1450
1982
  throw new Error("Response body is null");
1451
1983
  }
1984
+ let failedChunk = void 0;
1452
1985
  const transformStream = new TransformStream({
1453
1986
  start() {
1454
1987
  },
1455
1988
  async transform(chunk, controller) {
1456
1989
  try {
1457
1990
  const decoded = new TextDecoder().decode(chunk);
1458
- const chunks = decoded.split(RECORD_SEPARATOR2);
1991
+ const chunks = decoded.split(RECORD_SEPARATOR);
1459
1992
  for (const chunk2 of chunks) {
1460
1993
  if (chunk2) {
1994
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1461
1995
  try {
1462
- const parsedChunk = JSON.parse(chunk2);
1996
+ const parsedChunk = JSON.parse(newChunk);
1463
1997
  controller.enqueue(parsedChunk);
1998
+ failedChunk = void 0;
1464
1999
  } catch {
2000
+ failedChunk = newChunk;
1465
2001
  }
1466
2002
  }
1467
2003
  }
@@ -1483,9 +2019,64 @@ var Workflow = class extends BaseResource {
1483
2019
  body: {
1484
2020
  step: params.step,
1485
2021
  resumeData: params.resumeData,
1486
- 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
+ }
1487
2077
  }
1488
2078
  });
2079
+ return response.body.pipeThrough(transformStream);
1489
2080
  }
1490
2081
  /**
1491
2082
  * Watches workflow transitions in real-time
@@ -1523,7 +2114,7 @@ var Workflow = class extends BaseResource {
1523
2114
  async start(controller) {
1524
2115
  try {
1525
2116
  for await (const record of records) {
1526
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2117
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
1527
2118
  controller.enqueue(encoder.encode(json));
1528
2119
  }
1529
2120
  controller.close();
@@ -1546,22 +2137,38 @@ var A2A = class extends BaseResource {
1546
2137
  * @returns Promise containing the agent card information
1547
2138
  */
1548
2139
  async getCard() {
1549
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2140
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1550
2141
  }
1551
2142
  /**
1552
- * Send a message to the agent and get a response
2143
+ * Send a message to the agent and gets a message or task response
1553
2144
  * @param params - Parameters for the task
1554
- * @returns Promise containing the task response
2145
+ * @returns Promise containing the response
1555
2146
  */
1556
2147
  async sendMessage(params) {
1557
2148
  const response = await this.request(`/a2a/${this.agentId}`, {
1558
2149
  method: "POST",
1559
2150
  body: {
1560
- 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",
1561
2168
  params
1562
2169
  }
1563
2170
  });
1564
- return { task: response.result };
2171
+ return response;
1565
2172
  }
1566
2173
  /**
1567
2174
  * Get the status and result of a task
@@ -1576,7 +2183,7 @@ var A2A = class extends BaseResource {
1576
2183
  params
1577
2184
  }
1578
2185
  });
1579
- return response.result;
2186
+ return response;
1580
2187
  }
1581
2188
  /**
1582
2189
  * Cancel a running task
@@ -1592,21 +2199,6 @@ var A2A = class extends BaseResource {
1592
2199
  }
1593
2200
  });
1594
2201
  }
1595
- /**
1596
- * Send a message and subscribe to streaming updates (not fully implemented)
1597
- * @param params - Parameters for the task
1598
- * @returns Promise containing the task response
1599
- */
1600
- async sendAndSubscribe(params) {
1601
- return this.request(`/a2a/${this.agentId}`, {
1602
- method: "POST",
1603
- body: {
1604
- method: "tasks/sendSubscribe",
1605
- params
1606
- },
1607
- stream: true
1608
- });
1609
- }
1610
2202
  };
1611
2203
 
1612
2204
  // src/resources/mcp-tool.ts
@@ -1620,10 +2212,11 @@ var MCPTool = class extends BaseResource {
1620
2212
  }
1621
2213
  /**
1622
2214
  * Retrieves details about this specific tool from the MCP server.
2215
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1623
2216
  * @returns Promise containing the tool's information (name, description, schema).
1624
2217
  */
1625
- details() {
1626
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2218
+ details(runtimeContext) {
2219
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1627
2220
  }
1628
2221
  /**
1629
2222
  * Executes this specific tool on the MCP server.
@@ -1643,93 +2236,286 @@ var MCPTool = class extends BaseResource {
1643
2236
  }
1644
2237
  };
1645
2238
 
1646
- // src/resources/vNextNetwork.ts
1647
- var RECORD_SEPARATOR3 = "";
1648
- var VNextNetwork = class extends BaseResource {
1649
- constructor(options, networkId) {
2239
+ // src/resources/agent-builder.ts
2240
+ var RECORD_SEPARATOR2 = "";
2241
+ var AgentBuilder = class extends BaseResource {
2242
+ constructor(options, actionId) {
1650
2243
  super(options);
1651
- this.networkId = networkId;
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
+ );
1652
2283
  }
1653
2284
  /**
1654
- * Retrieves details about the network
1655
- * @returns Promise containing vNext network details
2285
+ * Creates a new agent builder action run and returns the runId.
2286
+ * This calls `/api/agent-builder/:actionId/create-run`.
1656
2287
  */
1657
- details() {
1658
- return this.request(`/api/networks/v-next/${this.networkId}`);
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
+ });
1659
2297
  }
1660
2298
  /**
1661
- * Generates a response from the v-next network
1662
- * @param params - Generation parameters including message
1663
- * @returns Promise containing the generated response
2299
+ * Starts agent builder action asynchronously and waits for completion.
2300
+ * This calls `/api/agent-builder/:actionId/start-async`.
1664
2301
  */
1665
- generate(params) {
1666
- return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
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, {
1667
2311
  method: "POST",
1668
- body: params
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
+ }
1669
2453
  });
2454
+ return response.body.pipeThrough(transformStream);
1670
2455
  }
1671
2456
  /**
1672
- * Generates a response from the v-next network using multiple primitives
1673
- * @param params - Generation parameters including message
1674
- * @returns Promise containing the generated response
2457
+ * Streams agent builder action progress in real-time using VNext streaming.
2458
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
1675
2459
  */
1676
- loop(params) {
1677
- return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
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, {
1678
2469
  method: "POST",
1679
- body: params
2470
+ body: { ...actionParams, runtimeContext },
2471
+ stream: true
1680
2472
  });
1681
- }
1682
- async *streamProcessor(stream) {
1683
- const reader = stream.getReader();
1684
- let doneReading = false;
1685
- let buffer = "";
1686
- try {
1687
- while (!doneReading) {
1688
- const { done, value } = await reader.read();
1689
- doneReading = done;
1690
- if (done && !value) continue;
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) {
1691
2484
  try {
1692
- const decoded = value ? new TextDecoder().decode(value) : "";
1693
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1694
- buffer = chunks.pop() || "";
1695
- for (const chunk of chunks) {
1696
- if (chunk) {
1697
- if (typeof chunk === "string") {
1698
- try {
1699
- const parsedChunk = JSON.parse(chunk);
1700
- yield parsedChunk;
1701
- } catch {
1702
- }
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;
1703
2496
  }
1704
2497
  }
1705
2498
  }
1706
2499
  } catch {
1707
2500
  }
1708
2501
  }
1709
- if (buffer) {
1710
- try {
1711
- yield JSON.parse(buffer);
1712
- } catch {
1713
- }
1714
- }
1715
- } finally {
1716
- reader.cancel().catch(() => {
1717
- });
1718
- }
2502
+ });
2503
+ return response.body.pipeThrough(transformStream);
1719
2504
  }
1720
2505
  /**
1721
- * Streams a response from the v-next network
1722
- * @param params - Stream parameters including message
1723
- * @returns Promise containing the results
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`.
1724
2510
  */
1725
- async stream(params, onRecord) {
1726
- const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1727
- method: "POST",
1728
- body: params,
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",
1729
2515
  stream: true
1730
2516
  });
1731
2517
  if (!response.ok) {
1732
- throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2518
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
1733
2519
  }
1734
2520
  if (!response.body) {
1735
2521
  throw new Error("Response body is null");
@@ -1743,29 +2529,155 @@ var VNextNetwork = class extends BaseResource {
1743
2529
  }
1744
2530
  }
1745
2531
  /**
1746
- * Streams a response from the v-next network loop
1747
- * @param params - Stream parameters including message
1748
- * @returns Promise containing the results
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
+ });
2574
+ }
2575
+ /**
2576
+ * Gets the execution result of an agent builder action run.
2577
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2578
+ */
2579
+ async runExecutionResult(runId) {
2580
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2581
+ return this.request(url, {
2582
+ method: "GET"
2583
+ });
2584
+ }
2585
+ /**
2586
+ * Cancels an agent builder action run.
2587
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2588
+ */
2589
+ async cancelRun(runId) {
2590
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2591
+ return this.request(url, {
2592
+ method: "POST"
2593
+ });
2594
+ }
2595
+ /**
2596
+ * Sends an event to an agent builder action run.
2597
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
1749
2598
  */
1750
- async loopStream(params, onRecord) {
1751
- const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
2599
+ async sendRunEvent(params) {
2600
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2601
+ return this.request(url, {
1752
2602
  method: "POST",
1753
- body: params,
1754
- stream: true
2603
+ body: { event: params.event, data: params.data }
1755
2604
  });
1756
- if (!response.ok) {
1757
- throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2605
+ }
2606
+ };
2607
+
2608
+ // src/resources/observability.ts
2609
+ var Observability = class extends BaseResource {
2610
+ constructor(options) {
2611
+ super(options);
2612
+ }
2613
+ /**
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
2617
+ */
2618
+ getTrace(traceId) {
2619
+ return this.request(`/api/observability/traces/${traceId}`);
2620
+ }
2621
+ /**
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
2625
+ */
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));
1758
2633
  }
1759
- if (!response.body) {
1760
- throw new Error("Response body is null");
2634
+ if (perPage !== void 0) {
2635
+ searchParams.set("perPage", String(perPage));
1761
2636
  }
1762
- for await (const record of this.streamProcessor(response.body)) {
1763
- if (typeof record === "string") {
1764
- onRecord(JSON.parse(record));
1765
- } else {
1766
- onRecord(record);
1767
- }
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));
1768
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`, {
2678
+ method: "POST",
2679
+ body: { ...params }
2680
+ });
1769
2681
  }
1770
2682
  };
1771
2683
 
@@ -1815,34 +2727,43 @@ var NetworkMemoryThread = class extends BaseResource {
1815
2727
  });
1816
2728
  return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1817
2729
  }
2730
+ /**
2731
+ * Deletes one or more messages from the thread
2732
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2733
+ * message object with id property, or array of message objects
2734
+ * @returns Promise containing deletion result
2735
+ */
2736
+ deleteMessages(messageIds) {
2737
+ const query = new URLSearchParams({
2738
+ networkId: this.networkId
2739
+ });
2740
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2741
+ method: "POST",
2742
+ body: { messageIds }
2743
+ });
2744
+ }
1818
2745
  };
1819
2746
 
1820
2747
  // src/client.ts
1821
2748
  var MastraClient = class extends BaseResource {
2749
+ observability;
1822
2750
  constructor(options) {
1823
2751
  super(options);
2752
+ this.observability = new Observability(options);
1824
2753
  }
1825
2754
  /**
1826
2755
  * Retrieves all available agents
2756
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1827
2757
  * @returns Promise containing map of agent IDs to agent details
1828
2758
  */
1829
- getAgents() {
1830
- return this.request("/api/agents");
1831
- }
1832
- async getAGUI({ resourceId }) {
1833
- const agents = await this.getAgents();
1834
- return Object.entries(agents).reduce(
1835
- (acc, [agentId]) => {
1836
- const agent = this.getAgent(agentId);
1837
- acc[agentId] = new AGUIAdapter({
1838
- agentId,
1839
- agent,
1840
- resourceId
1841
- });
1842
- return acc;
1843
- },
1844
- {}
1845
- );
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}` : ""}`);
1846
2767
  }
1847
2768
  /**
1848
2769
  * Gets an agent instance by ID
@@ -1860,6 +2781,14 @@ var MastraClient = class extends BaseResource {
1860
2781
  getMemoryThreads(params) {
1861
2782
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1862
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
+ }
1863
2792
  /**
1864
2793
  * Creates a new memory thread
1865
2794
  * @param params - Parameters for creating the memory thread
@@ -1876,6 +2805,24 @@ var MastraClient = class extends BaseResource {
1876
2805
  getMemoryThread(threadId, agentId) {
1877
2806
  return new MemoryThread(this.options, threadId, agentId);
1878
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
+ }
1879
2826
  /**
1880
2827
  * Saves messages to memory
1881
2828
  * @param params - Parameters containing messages to save
@@ -1938,10 +2885,17 @@ var MastraClient = class extends BaseResource {
1938
2885
  }
1939
2886
  /**
1940
2887
  * Retrieves all available tools
2888
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1941
2889
  * @returns Promise containing map of tool IDs to tool details
1942
2890
  */
1943
- getTools() {
1944
- 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}` : ""}`);
1945
2899
  }
1946
2900
  /**
1947
2901
  * Gets a tool instance by ID
@@ -1949,29 +2903,21 @@ var MastraClient = class extends BaseResource {
1949
2903
  * @returns Tool instance
1950
2904
  */
1951
2905
  getTool(toolId) {
1952
- return new Tool2(this.options, toolId);
1953
- }
1954
- /**
1955
- * Retrieves all available legacy workflows
1956
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1957
- */
1958
- getLegacyWorkflows() {
1959
- return this.request("/api/workflows/legacy");
1960
- }
1961
- /**
1962
- * Gets a legacy workflow instance by ID
1963
- * @param workflowId - ID of the legacy workflow to retrieve
1964
- * @returns Legacy Workflow instance
1965
- */
1966
- getLegacyWorkflow(workflowId) {
1967
- return new LegacyWorkflow(this.options, workflowId);
2906
+ return new Tool(this.options, toolId);
1968
2907
  }
1969
2908
  /**
1970
2909
  * Retrieves all available workflows
2910
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1971
2911
  * @returns Promise containing map of workflow IDs to workflow details
1972
2912
  */
1973
- getWorkflows() {
1974
- 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}` : ""}`);
1975
2921
  }
1976
2922
  /**
1977
2923
  * Gets a workflow instance by ID
@@ -1981,6 +2927,20 @@ var MastraClient = class extends BaseResource {
1981
2927
  getWorkflow(workflowId) {
1982
2928
  return new Workflow(this.options, workflowId);
1983
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
+ }
1984
2944
  /**
1985
2945
  * Gets a vector instance by name
1986
2946
  * @param vectorName - Name of the vector to retrieve
@@ -2125,36 +3085,6 @@ var MastraClient = class extends BaseResource {
2125
3085
  return this.request(`/api/telemetry`);
2126
3086
  }
2127
3087
  }
2128
- /**
2129
- * Retrieves all available networks
2130
- * @returns Promise containing map of network IDs to network details
2131
- */
2132
- getNetworks() {
2133
- return this.request("/api/networks");
2134
- }
2135
- /**
2136
- * Retrieves all available vNext networks
2137
- * @returns Promise containing map of vNext network IDs to vNext network details
2138
- */
2139
- getVNextNetworks() {
2140
- return this.request("/api/networks/v-next");
2141
- }
2142
- /**
2143
- * Gets a network instance by ID
2144
- * @param networkId - ID of the network to retrieve
2145
- * @returns Network instance
2146
- */
2147
- getNetwork(networkId) {
2148
- return new Network(this.options, networkId);
2149
- }
2150
- /**
2151
- * Gets a vNext network instance by ID
2152
- * @param networkId - ID of the vNext network to retrieve
2153
- * @returns vNext Network instance
2154
- */
2155
- getVNextNetwork(networkId) {
2156
- return new VNextNetwork(this.options, networkId);
2157
- }
2158
3088
  /**
2159
3089
  * Retrieves a list of available MCP servers.
2160
3090
  * @param params - Optional parameters for pagination (limit, offset).
@@ -2211,6 +3141,163 @@ var MastraClient = class extends BaseResource {
2211
3141
  getA2A(agentId) {
2212
3142
  return new A2A(this.options, agentId);
2213
3143
  }
3144
+ /**
3145
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3146
+ * @param agentId - ID of the agent.
3147
+ * @param threadId - ID of the thread.
3148
+ * @param resourceId - Optional ID of the resource.
3149
+ * @returns Working memory for the specified thread or resource.
3150
+ */
3151
+ getWorkingMemory({
3152
+ agentId,
3153
+ threadId,
3154
+ resourceId
3155
+ }) {
3156
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3157
+ }
3158
+ /**
3159
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3160
+ * @param agentId - ID of the agent.
3161
+ * @param threadId - ID of the thread.
3162
+ * @param workingMemory - The new working memory content.
3163
+ * @param resourceId - Optional ID of the resource.
3164
+ */
3165
+ updateWorkingMemory({
3166
+ agentId,
3167
+ threadId,
3168
+ workingMemory,
3169
+ resourceId
3170
+ }) {
3171
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3172
+ method: "POST",
3173
+ body: {
3174
+ workingMemory,
3175
+ resourceId
3176
+ }
3177
+ });
3178
+ }
3179
+ /**
3180
+ * Retrieves all available scorers
3181
+ * @returns Promise containing list of available scorers
3182
+ */
3183
+ getScorers() {
3184
+ return this.request("/api/scores/scorers");
3185
+ }
3186
+ /**
3187
+ * Retrieves a scorer by ID
3188
+ * @param scorerId - ID of the scorer to retrieve
3189
+ * @returns Promise containing the scorer
3190
+ */
3191
+ getScorer(scorerId) {
3192
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3193
+ }
3194
+ getScoresByScorerId(params) {
3195
+ const { page, perPage, scorerId, entityId, entityType } = params;
3196
+ const searchParams = new URLSearchParams();
3197
+ if (entityId) {
3198
+ searchParams.set("entityId", entityId);
3199
+ }
3200
+ if (entityType) {
3201
+ searchParams.set("entityType", entityType);
3202
+ }
3203
+ if (page !== void 0) {
3204
+ searchParams.set("page", String(page));
3205
+ }
3206
+ if (perPage !== void 0) {
3207
+ searchParams.set("perPage", String(perPage));
3208
+ }
3209
+ const queryString = searchParams.toString();
3210
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3211
+ }
3212
+ /**
3213
+ * Retrieves scores by run ID
3214
+ * @param params - Parameters containing run ID and pagination options
3215
+ * @returns Promise containing scores and pagination info
3216
+ */
3217
+ getScoresByRunId(params) {
3218
+ const { runId, page, perPage } = params;
3219
+ const searchParams = new URLSearchParams();
3220
+ if (page !== void 0) {
3221
+ searchParams.set("page", String(page));
3222
+ }
3223
+ if (perPage !== void 0) {
3224
+ searchParams.set("perPage", String(perPage));
3225
+ }
3226
+ const queryString = searchParams.toString();
3227
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3228
+ }
3229
+ /**
3230
+ * Retrieves scores by entity ID and type
3231
+ * @param params - Parameters containing entity ID, type, and pagination options
3232
+ * @returns Promise containing scores and pagination info
3233
+ */
3234
+ getScoresByEntityId(params) {
3235
+ const { entityId, entityType, page, perPage } = params;
3236
+ const searchParams = new URLSearchParams();
3237
+ if (page !== void 0) {
3238
+ searchParams.set("page", String(page));
3239
+ }
3240
+ if (perPage !== void 0) {
3241
+ searchParams.set("perPage", String(perPage));
3242
+ }
3243
+ const queryString = searchParams.toString();
3244
+ return this.request(
3245
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3246
+ );
3247
+ }
3248
+ /**
3249
+ * Saves a score
3250
+ * @param params - Parameters containing the score data to save
3251
+ * @returns Promise containing the saved score
3252
+ */
3253
+ saveScore(params) {
3254
+ return this.request("/api/scores", {
3255
+ method: "POST",
3256
+ body: params
3257
+ });
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
+ }
2214
3278
  };
2215
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;
2216
3300
  exports.MastraClient = MastraClient;
3301
+ exports.createTool = createTool;
3302
+ //# sourceMappingURL=index.cjs.map
3303
+ //# sourceMappingURL=index.cjs.map