@mastra/client-js 0.0.0-support-d1-client-20250701191943 → 0.0.0-suspendRuntimeContextTypeFix-20250930142630

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 (80) hide show
  1. package/CHANGELOG.md +1305 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +7 -8
  4. package/dist/client.d.ts +290 -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 +1858 -691
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -1152
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +1856 -691
  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 +191 -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/vNextNetwork.d.ts +43 -0
  35. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  36. package/dist/resources/vector.d.ts +51 -0
  37. package/dist/resources/vector.d.ts.map +1 -0
  38. package/dist/resources/workflow.d.ts +264 -0
  39. package/dist/resources/workflow.d.ts.map +1 -0
  40. package/dist/tools.d.ts +22 -0
  41. package/dist/tools.d.ts.map +1 -0
  42. package/dist/types.d.ts +476 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/utils/index.d.ts +5 -0
  45. package/dist/utils/index.d.ts.map +1 -0
  46. package/dist/utils/process-client-tools.d.ts +3 -0
  47. package/dist/utils/process-client-tools.d.ts.map +1 -0
  48. package/dist/utils/process-mastra-stream.d.ts +11 -0
  49. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  50. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  51. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  52. package/package.json +27 -15
  53. package/.turbo/turbo-build.log +0 -19
  54. package/dist/index.d.cts +0 -1152
  55. package/eslint.config.js +0 -6
  56. package/src/adapters/agui.test.ts +0 -180
  57. package/src/adapters/agui.ts +0 -239
  58. package/src/client.ts +0 -480
  59. package/src/example.ts +0 -67
  60. package/src/index.test.ts +0 -830
  61. package/src/index.ts +0 -2
  62. package/src/resources/a2a.ts +0 -88
  63. package/src/resources/agent.ts +0 -763
  64. package/src/resources/base.ts +0 -71
  65. package/src/resources/index.ts +0 -10
  66. package/src/resources/legacy-workflow.ts +0 -242
  67. package/src/resources/mcp-tool.ts +0 -48
  68. package/src/resources/memory-thread.ts +0 -63
  69. package/src/resources/network-memory-thread.ts +0 -63
  70. package/src/resources/network.ts +0 -85
  71. package/src/resources/tool.ts +0 -45
  72. package/src/resources/vNextNetwork.ts +0 -177
  73. package/src/resources/vector.ts +0 -83
  74. package/src/resources/workflow.ts +0 -384
  75. package/src/types.ts +0 -422
  76. package/src/utils/index.ts +0 -11
  77. package/src/utils/process-client-tools.ts +0 -32
  78. package/src/utils/zod-to-json-schema.ts +0 -10
  79. package/tsconfig.json +0 -5
  80. 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,19 @@ 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
326
  async generate(params) {
327
+ console.warn(
328
+ "Deprecation NOTICE:Generate method will switch to use generateVNext implementation September 30th, 2025. Please use generateLegacy if you don't want to upgrade just yet."
329
+ );
330
+ return this.generateLegacy(params);
331
+ }
332
+ async generateLegacy(params) {
371
333
  const processedParams = {
372
334
  ...params,
373
335
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -376,26 +338,38 @@ var Agent = class extends BaseResource {
376
338
  clientTools: processClientTools(params.clientTools)
377
339
  };
378
340
  const { runId, resourceId, threadId, runtimeContext } = processedParams;
379
- const response = await this.request(`/api/agents/${this.agentId}/generate`, {
380
- method: "POST",
381
- body: processedParams
382
- });
341
+ const response = await this.request(
342
+ `/api/agents/${this.agentId}/generate-legacy`,
343
+ {
344
+ method: "POST",
345
+ body: processedParams
346
+ }
347
+ );
383
348
  if (response.finishReason === "tool-calls") {
384
- for (const toolCall of response.toolCalls) {
349
+ const toolCalls = response.toolCalls;
350
+ if (!toolCalls || !Array.isArray(toolCalls)) {
351
+ return response;
352
+ }
353
+ for (const toolCall of toolCalls) {
385
354
  const clientTool = params.clientTools?.[toolCall.toolName];
386
355
  if (clientTool && clientTool.execute) {
387
356
  const result = await clientTool.execute(
388
- { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
357
+ {
358
+ context: toolCall?.args,
359
+ runId,
360
+ resourceId,
361
+ threadId,
362
+ runtimeContext,
363
+ tracingContext: { currentSpan: void 0 },
364
+ suspend: async () => {
365
+ }
366
+ },
389
367
  {
390
368
  messages: response.messages,
391
369
  toolCallId: toolCall?.toolCallId
392
370
  }
393
371
  );
394
372
  const updatedMessages = [
395
- {
396
- role: "user",
397
- content: params.messages
398
- },
399
373
  ...response.response.messages,
400
374
  {
401
375
  role: "tool",
@@ -418,6 +392,47 @@ var Agent = class extends BaseResource {
418
392
  }
419
393
  return response;
420
394
  }
395
+ async generateVNext(messagesOrParams, options) {
396
+ let params;
397
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
398
+ params = messagesOrParams;
399
+ } else {
400
+ params = {
401
+ messages: messagesOrParams,
402
+ ...options
403
+ };
404
+ }
405
+ const processedParams = {
406
+ ...params,
407
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
408
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
409
+ clientTools: processClientTools(params.clientTools),
410
+ structuredOutput: params.structuredOutput ? {
411
+ ...params.structuredOutput,
412
+ schema: zodToJsonSchema(params.structuredOutput.schema)
413
+ } : void 0
414
+ };
415
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
416
+ const response = await this.request(
417
+ `/api/agents/${this.agentId}/generate/vnext`,
418
+ {
419
+ method: "POST",
420
+ body: processedParams
421
+ }
422
+ );
423
+ if (response.finishReason === "tool-calls") {
424
+ return executeToolCallAndRespond({
425
+ response,
426
+ params,
427
+ runId,
428
+ resourceId,
429
+ threadId,
430
+ runtimeContext,
431
+ respondFn: this.generateVNext.bind(this)
432
+ });
433
+ }
434
+ return response;
435
+ }
421
436
  async processChatResponse({
422
437
  stream,
423
438
  update,
@@ -432,7 +447,7 @@ var Agent = class extends BaseResource {
432
447
  return Math.max(max, toolInvocation.step ?? 0);
433
448
  }, 0) ?? 0) : 0;
434
449
  const message = replaceLastMessage ? structuredClone(lastMessage) : {
435
- id: crypto.randomUUID(),
450
+ id: uuid.v4(),
436
451
  createdAt: getCurrentDate(),
437
452
  role: "assistant",
438
453
  content: "",
@@ -477,7 +492,7 @@ var Agent = class extends BaseResource {
477
492
  // changes. This is why we need to add a revision id to ensure that the message
478
493
  // is updated with SWR (without it, the changes get stuck in SWR and are not
479
494
  // forwarded to rendering):
480
- revisionId: crypto.randomUUID()
495
+ revisionId: uuid.v4()
481
496
  };
482
497
  update({
483
498
  message: copiedMessage,
@@ -686,6 +701,17 @@ var Agent = class extends BaseResource {
686
701
  * @returns Promise containing the enhanced Response object with processDataStream method
687
702
  */
688
703
  async stream(params) {
704
+ console.warn(
705
+ "Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 30th, 2025. Please use streamLegacy if you don't want to upgrade just yet."
706
+ );
707
+ return this.streamLegacy(params);
708
+ }
709
+ /**
710
+ * Streams a response from the agent
711
+ * @param params - Stream parameters including prompt
712
+ * @returns Promise containing the enhanced Response object with processDataStream method
713
+ */
714
+ async streamLegacy(params) {
689
715
  const processedParams = {
690
716
  ...params,
691
717
  output: params.output ? zodToJsonSchema(params.output) : void 0,
@@ -708,11 +734,261 @@ var Agent = class extends BaseResource {
708
734
  };
709
735
  return streamResponse;
710
736
  }
711
- /**
712
- * Processes the stream response and handles tool calls
713
- */
714
- async processStreamResponse(processedParams, writable) {
715
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
737
+ async processChatResponse_vNext({
738
+ stream,
739
+ update,
740
+ onToolCall,
741
+ onFinish,
742
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
743
+ lastMessage
744
+ }) {
745
+ const replaceLastMessage = lastMessage?.role === "assistant";
746
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
747
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
748
+ return Math.max(max, toolInvocation.step ?? 0);
749
+ }, 0) ?? 0) : 0;
750
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
751
+ id: uuid.v4(),
752
+ createdAt: getCurrentDate(),
753
+ role: "assistant",
754
+ content: "",
755
+ parts: []
756
+ };
757
+ let currentTextPart = void 0;
758
+ let currentReasoningPart = void 0;
759
+ let currentReasoningTextDetail = void 0;
760
+ function updateToolInvocationPart(toolCallId, invocation) {
761
+ const part = message.parts.find(
762
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
763
+ );
764
+ if (part != null) {
765
+ part.toolInvocation = invocation;
766
+ } else {
767
+ message.parts.push({
768
+ type: "tool-invocation",
769
+ toolInvocation: invocation
770
+ });
771
+ }
772
+ }
773
+ const data = [];
774
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
775
+ const partialToolCalls = {};
776
+ let usage = {
777
+ completionTokens: NaN,
778
+ promptTokens: NaN,
779
+ totalTokens: NaN
780
+ };
781
+ let finishReason = "unknown";
782
+ function execUpdate() {
783
+ const copiedData = [...data];
784
+ if (messageAnnotations?.length) {
785
+ message.annotations = messageAnnotations;
786
+ }
787
+ const copiedMessage = {
788
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
789
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
790
+ ...structuredClone(message),
791
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
792
+ // hashing approach by default to detect changes, but it only works for shallow
793
+ // changes. This is why we need to add a revision id to ensure that the message
794
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
795
+ // forwarded to rendering):
796
+ revisionId: uuid.v4()
797
+ };
798
+ update({
799
+ message: copiedMessage,
800
+ data: copiedData,
801
+ replaceLastMessage
802
+ });
803
+ }
804
+ await processMastraStream({
805
+ stream,
806
+ // TODO: casting as any here because the stream types were all typed as any before in core.
807
+ // but this is completely wrong and this fn is probably broken. Remove ":any" and you'll see a bunch of type errors
808
+ onChunk: async (chunk) => {
809
+ switch (chunk.type) {
810
+ case "step-start": {
811
+ if (!replaceLastMessage) {
812
+ message.id = chunk.payload.messageId;
813
+ }
814
+ message.parts.push({ type: "step-start" });
815
+ execUpdate();
816
+ break;
817
+ }
818
+ case "text-delta": {
819
+ if (currentTextPart == null) {
820
+ currentTextPart = {
821
+ type: "text",
822
+ text: chunk.payload.text
823
+ };
824
+ message.parts.push(currentTextPart);
825
+ } else {
826
+ currentTextPart.text += chunk.payload.text;
827
+ }
828
+ message.content += chunk.payload.text;
829
+ execUpdate();
830
+ break;
831
+ }
832
+ case "reasoning-delta": {
833
+ if (currentReasoningTextDetail == null) {
834
+ currentReasoningTextDetail = { type: "text", text: chunk.payload.text };
835
+ if (currentReasoningPart != null) {
836
+ currentReasoningPart.details.push(currentReasoningTextDetail);
837
+ }
838
+ } else {
839
+ currentReasoningTextDetail.text += chunk.payload.text;
840
+ }
841
+ if (currentReasoningPart == null) {
842
+ currentReasoningPart = {
843
+ type: "reasoning",
844
+ reasoning: chunk.payload.text,
845
+ details: [currentReasoningTextDetail]
846
+ };
847
+ message.parts.push(currentReasoningPart);
848
+ } else {
849
+ currentReasoningPart.reasoning += chunk.payload.text;
850
+ }
851
+ message.reasoning = (message.reasoning ?? "") + chunk.payload.text;
852
+ execUpdate();
853
+ break;
854
+ }
855
+ case "file": {
856
+ message.parts.push({
857
+ type: "file",
858
+ mimeType: chunk.payload.mimeType,
859
+ data: chunk.payload.data
860
+ });
861
+ execUpdate();
862
+ break;
863
+ }
864
+ case "source": {
865
+ message.parts.push({
866
+ type: "source",
867
+ source: chunk.payload.source
868
+ });
869
+ execUpdate();
870
+ break;
871
+ }
872
+ case "tool-call": {
873
+ const invocation = {
874
+ state: "call",
875
+ step,
876
+ ...chunk.payload
877
+ };
878
+ if (partialToolCalls[chunk.payload.toolCallId] != null) {
879
+ message.toolInvocations[partialToolCalls[chunk.payload.toolCallId].index] = invocation;
880
+ } else {
881
+ if (message.toolInvocations == null) {
882
+ message.toolInvocations = [];
883
+ }
884
+ message.toolInvocations.push(invocation);
885
+ }
886
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
887
+ execUpdate();
888
+ if (onToolCall) {
889
+ const result = await onToolCall({ toolCall: chunk.payload });
890
+ if (result != null) {
891
+ const invocation2 = {
892
+ state: "result",
893
+ step,
894
+ ...chunk.payload,
895
+ result
896
+ };
897
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
898
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation2);
899
+ execUpdate();
900
+ }
901
+ }
902
+ }
903
+ case "tool-call-input-streaming-start": {
904
+ if (message.toolInvocations == null) {
905
+ message.toolInvocations = [];
906
+ }
907
+ partialToolCalls[chunk.payload.toolCallId] = {
908
+ text: "",
909
+ step,
910
+ toolName: chunk.payload.toolName,
911
+ index: message.toolInvocations.length
912
+ };
913
+ const invocation = {
914
+ state: "partial-call",
915
+ step,
916
+ toolCallId: chunk.payload.toolCallId,
917
+ toolName: chunk.payload.toolName,
918
+ args: chunk.payload.args
919
+ };
920
+ message.toolInvocations.push(invocation);
921
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
922
+ execUpdate();
923
+ break;
924
+ }
925
+ case "tool-call-delta": {
926
+ const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
927
+ partialToolCall.text += chunk.payload.argsTextDelta;
928
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
929
+ const invocation = {
930
+ state: "partial-call",
931
+ step: partialToolCall.step,
932
+ toolCallId: chunk.payload.toolCallId,
933
+ toolName: partialToolCall.toolName,
934
+ args: partialArgs
935
+ };
936
+ message.toolInvocations[partialToolCall.index] = invocation;
937
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
938
+ execUpdate();
939
+ break;
940
+ }
941
+ case "tool-result": {
942
+ const toolInvocations = message.toolInvocations;
943
+ if (toolInvocations == null) {
944
+ throw new Error("tool_result must be preceded by a tool_call");
945
+ }
946
+ const toolInvocationIndex = toolInvocations.findIndex(
947
+ (invocation2) => invocation2.toolCallId === chunk.payload.toolCallId
948
+ );
949
+ if (toolInvocationIndex === -1) {
950
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
951
+ }
952
+ const invocation = {
953
+ ...toolInvocations[toolInvocationIndex],
954
+ state: "result",
955
+ ...chunk.payload
956
+ };
957
+ toolInvocations[toolInvocationIndex] = invocation;
958
+ updateToolInvocationPart(chunk.payload.toolCallId, invocation);
959
+ execUpdate();
960
+ break;
961
+ }
962
+ case "error": {
963
+ throw new Error(chunk.payload.error);
964
+ }
965
+ case "data": {
966
+ data.push(...chunk.payload.data);
967
+ execUpdate();
968
+ break;
969
+ }
970
+ case "step-finish": {
971
+ step += 1;
972
+ currentTextPart = chunk.payload.stepResult.isContinued ? currentTextPart : void 0;
973
+ currentReasoningPart = void 0;
974
+ currentReasoningTextDetail = void 0;
975
+ execUpdate();
976
+ break;
977
+ }
978
+ case "finish": {
979
+ finishReason = chunk.payload.stepResult.reason;
980
+ if (chunk.payload.usage != null) {
981
+ usage = chunk.payload.usage;
982
+ }
983
+ break;
984
+ }
985
+ }
986
+ }
987
+ });
988
+ onFinish?.({ message, finishReason, usage });
989
+ }
990
+ async processStreamResponse_vNext(processedParams, writable) {
991
+ const response = await this.request(`/api/agents/${this.agentId}/stream/vnext`, {
716
992
  method: "POST",
717
993
  body: processedParams,
718
994
  stream: true
@@ -724,15 +1000,210 @@ var Agent = class extends BaseResource {
724
1000
  let toolCalls = [];
725
1001
  let messages = [];
726
1002
  const [streamForWritable, streamForProcessing] = response.body.tee();
727
- streamForWritable.pipeTo(writable, {
728
- preventClose: true
729
- }).catch((error) => {
730
- console.error("Error piping to writable stream:", error);
731
- });
732
- this.processChatResponse({
733
- stream: streamForProcessing,
1003
+ streamForWritable.pipeTo(
1004
+ new WritableStream({
1005
+ async write(chunk) {
1006
+ try {
1007
+ const text = new TextDecoder().decode(chunk);
1008
+ if (text.includes("[DONE]")) {
1009
+ return;
1010
+ }
1011
+ } catch {
1012
+ }
1013
+ const writer = writable.getWriter();
1014
+ try {
1015
+ await writer.write(chunk);
1016
+ } finally {
1017
+ writer.releaseLock();
1018
+ }
1019
+ }
1020
+ }),
1021
+ {
1022
+ preventClose: true
1023
+ }
1024
+ ).catch((error) => {
1025
+ console.error("Error piping to writable stream:", error);
1026
+ });
1027
+ this.processChatResponse_vNext({
1028
+ stream: streamForProcessing,
1029
+ update: ({ message }) => {
1030
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1031
+ if (existingIndex !== -1) {
1032
+ messages[existingIndex] = message;
1033
+ } else {
1034
+ messages.push(message);
1035
+ }
1036
+ },
1037
+ onFinish: async ({ finishReason, message }) => {
1038
+ if (finishReason === "tool-calls") {
1039
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1040
+ if (toolCall) {
1041
+ toolCalls.push(toolCall);
1042
+ }
1043
+ let shouldExecuteClientTool = false;
1044
+ for (const toolCall2 of toolCalls) {
1045
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1046
+ if (clientTool && clientTool.execute) {
1047
+ shouldExecuteClientTool = true;
1048
+ const result = await clientTool.execute(
1049
+ {
1050
+ context: toolCall2?.args,
1051
+ runId: processedParams.runId,
1052
+ resourceId: processedParams.resourceId,
1053
+ threadId: processedParams.threadId,
1054
+ runtimeContext: processedParams.runtimeContext,
1055
+ // TODO: Pass proper tracing context when client-js supports tracing
1056
+ tracingContext: { currentSpan: void 0 },
1057
+ suspend: async () => {
1058
+ }
1059
+ },
1060
+ {
1061
+ messages: response.messages,
1062
+ toolCallId: toolCall2?.toolCallId
1063
+ }
1064
+ );
1065
+ const lastMessageRaw = messages[messages.length - 1];
1066
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1067
+ const toolInvocationPart = lastMessage?.parts?.find(
1068
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1069
+ );
1070
+ if (toolInvocationPart) {
1071
+ toolInvocationPart.toolInvocation = {
1072
+ ...toolInvocationPart.toolInvocation,
1073
+ state: "result",
1074
+ result
1075
+ };
1076
+ }
1077
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1078
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1079
+ );
1080
+ if (toolInvocation) {
1081
+ toolInvocation.state = "result";
1082
+ toolInvocation.result = result;
1083
+ }
1084
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1085
+ this.processStreamResponse_vNext(
1086
+ {
1087
+ ...processedParams,
1088
+ messages: updatedMessages
1089
+ },
1090
+ writable
1091
+ ).catch((error) => {
1092
+ console.error("Error processing stream response:", error);
1093
+ });
1094
+ }
1095
+ }
1096
+ if (!shouldExecuteClientTool) {
1097
+ setTimeout(() => {
1098
+ writable.close();
1099
+ }, 0);
1100
+ }
1101
+ } else {
1102
+ setTimeout(() => {
1103
+ writable.close();
1104
+ }, 0);
1105
+ }
1106
+ },
1107
+ lastMessage: void 0
1108
+ }).catch((error) => {
1109
+ console.error("Error processing stream response:", error);
1110
+ });
1111
+ } catch (error) {
1112
+ console.error("Error processing stream response:", error);
1113
+ }
1114
+ return response;
1115
+ }
1116
+ async network(params) {
1117
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1118
+ method: "POST",
1119
+ body: params,
1120
+ stream: true
1121
+ });
1122
+ if (!response.body) {
1123
+ throw new Error("No response body");
1124
+ }
1125
+ const streamResponse = new Response(response.body, {
1126
+ status: response.status,
1127
+ statusText: response.statusText,
1128
+ headers: response.headers
1129
+ });
1130
+ streamResponse.processDataStream = async ({
1131
+ onChunk
1132
+ }) => {
1133
+ await processMastraNetworkStream({
1134
+ stream: streamResponse.body,
1135
+ onChunk
1136
+ });
1137
+ };
1138
+ return streamResponse;
1139
+ }
1140
+ async streamVNext(messagesOrParams, options) {
1141
+ let params;
1142
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1143
+ params = messagesOrParams;
1144
+ } else {
1145
+ params = {
1146
+ messages: messagesOrParams,
1147
+ ...options
1148
+ };
1149
+ }
1150
+ const processedParams = {
1151
+ ...params,
1152
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1153
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1154
+ clientTools: processClientTools(params.clientTools),
1155
+ structuredOutput: params.structuredOutput ? {
1156
+ ...params.structuredOutput,
1157
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1158
+ } : void 0
1159
+ };
1160
+ const { readable, writable } = new TransformStream();
1161
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1162
+ const streamResponse = new Response(readable, {
1163
+ status: response.status,
1164
+ statusText: response.statusText,
1165
+ headers: response.headers
1166
+ });
1167
+ streamResponse.processDataStream = async ({
1168
+ onChunk
1169
+ }) => {
1170
+ await processMastraStream({
1171
+ stream: streamResponse.body,
1172
+ onChunk
1173
+ });
1174
+ };
1175
+ return streamResponse;
1176
+ }
1177
+ /**
1178
+ * Processes the stream response and handles tool calls
1179
+ */
1180
+ async processStreamResponse(processedParams, writable) {
1181
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1182
+ method: "POST",
1183
+ body: processedParams,
1184
+ stream: true
1185
+ });
1186
+ if (!response.body) {
1187
+ throw new Error("No response body");
1188
+ }
1189
+ try {
1190
+ let toolCalls = [];
1191
+ let messages = [];
1192
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1193
+ streamForWritable.pipeTo(writable, {
1194
+ preventClose: true
1195
+ }).catch((error) => {
1196
+ console.error("Error piping to writable stream:", error);
1197
+ });
1198
+ this.processChatResponse({
1199
+ stream: streamForProcessing,
734
1200
  update: ({ message }) => {
735
- messages.push(message);
1201
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1202
+ if (existingIndex !== -1) {
1203
+ messages[existingIndex] = message;
1204
+ } else {
1205
+ messages.push(message);
1206
+ }
736
1207
  },
737
1208
  onFinish: async ({ finishReason, message }) => {
738
1209
  if (finishReason === "tool-calls") {
@@ -749,7 +1220,11 @@ var Agent = class extends BaseResource {
749
1220
  runId: processedParams.runId,
750
1221
  resourceId: processedParams.resourceId,
751
1222
  threadId: processedParams.threadId,
752
- runtimeContext: processedParams.runtimeContext
1223
+ runtimeContext: processedParams.runtimeContext,
1224
+ // TODO: Pass proper tracing context when client-js supports tracing
1225
+ tracingContext: { currentSpan: void 0 },
1226
+ suspend: async () => {
1227
+ }
753
1228
  },
754
1229
  {
755
1230
  messages: response.messages,
@@ -787,15 +1262,15 @@ var Agent = class extends BaseResource {
787
1262
  } finally {
788
1263
  writer.releaseLock();
789
1264
  }
790
- const originalMessages = processedParams.messages;
791
- const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
792
1265
  this.processStreamResponse(
793
1266
  {
794
1267
  ...processedParams,
795
- messages: [...messageArray, ...messages, lastMessage]
1268
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
796
1269
  },
797
1270
  writable
798
- );
1271
+ ).catch((error) => {
1272
+ console.error("Error processing stream response:", error);
1273
+ });
799
1274
  }
800
1275
  }
801
1276
  } else {
@@ -805,6 +1280,8 @@ var Agent = class extends BaseResource {
805
1280
  }
806
1281
  },
807
1282
  lastMessage: void 0
1283
+ }).catch((error) => {
1284
+ console.error("Error processing stream response:", error);
808
1285
  });
809
1286
  } catch (error) {
810
1287
  console.error("Error processing stream response:", error);
@@ -814,10 +1291,11 @@ var Agent = class extends BaseResource {
814
1291
  /**
815
1292
  * Gets details about a specific tool available to the agent
816
1293
  * @param toolId - ID of the tool to retrieve
1294
+ * @param runtimeContext - Optional runtime context to pass as query parameter
817
1295
  * @returns Promise containing tool details
818
1296
  */
819
- getTool(toolId) {
820
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
1297
+ getTool(toolId, runtimeContext) {
1298
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
821
1299
  }
822
1300
  /**
823
1301
  * Executes a tool for the agent
@@ -828,7 +1306,7 @@ var Agent = class extends BaseResource {
828
1306
  executeTool(toolId, params) {
829
1307
  const body = {
830
1308
  data: params.data,
831
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
1309
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
832
1310
  };
833
1311
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
834
1312
  method: "POST",
@@ -837,73 +1315,52 @@ var Agent = class extends BaseResource {
837
1315
  }
838
1316
  /**
839
1317
  * Retrieves evaluation results for the agent
1318
+ * @param runtimeContext - Optional runtime context to pass as query parameter
840
1319
  * @returns Promise containing agent evaluations
841
1320
  */
842
- evals() {
843
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
1321
+ evals(runtimeContext) {
1322
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
844
1323
  }
845
1324
  /**
846
1325
  * Retrieves live evaluation results for the agent
1326
+ * @param runtimeContext - Optional runtime context to pass as query parameter
847
1327
  * @returns Promise containing live agent evaluations
848
1328
  */
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;
1329
+ liveEvals(runtimeContext) {
1330
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
857
1331
  }
858
1332
  /**
859
- * Retrieves details about the network
860
- * @returns Promise containing network details
1333
+ * Updates the model for the agent
1334
+ * @param params - Parameters for updating the model
1335
+ * @returns Promise containing the updated model
861
1336
  */
862
- details() {
863
- return this.request(`/api/networks/${this.networkId}`);
1337
+ updateModel(params) {
1338
+ return this.request(`/api/agents/${this.agentId}/model`, {
1339
+ method: "POST",
1340
+ body: params
1341
+ });
864
1342
  }
865
1343
  /**
866
- * Generates a response from the agent
867
- * @param params - Generation parameters including prompt
868
- * @returns Promise containing the generated response
1344
+ * Updates the model for the agent in the model list
1345
+ * @param params - Parameters for updating the model
1346
+ * @returns Promise containing the updated model
869
1347
  */
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`, {
1348
+ updateModelInModelList({ modelConfigId, ...params }) {
1349
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
877
1350
  method: "POST",
878
- body: processedParams
1351
+ body: params
879
1352
  });
880
1353
  }
881
1354
  /**
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
1355
+ * Reorders the models for the agent
1356
+ * @param params - Parameters for reordering the model list
1357
+ * @returns Promise containing the updated model list
885
1358
  */
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`, {
1359
+ reorderModelList(params) {
1360
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
893
1361
  method: "POST",
894
- body: processedParams,
895
- stream: true
1362
+ body: params
896
1363
  });
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;
907
1364
  }
908
1365
  };
909
1366
 
@@ -953,6 +1410,36 @@ var MemoryThread = class extends BaseResource {
953
1410
  });
954
1411
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
955
1412
  }
1413
+ /**
1414
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1415
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1416
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1417
+ */
1418
+ getMessagesPaginated({
1419
+ selectBy,
1420
+ ...rest
1421
+ }) {
1422
+ const query = new URLSearchParams({
1423
+ ...rest,
1424
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1425
+ });
1426
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1427
+ }
1428
+ /**
1429
+ * Deletes one or more messages from the thread
1430
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1431
+ * message object with id property, or array of message objects
1432
+ * @returns Promise containing deletion result
1433
+ */
1434
+ deleteMessages(messageIds) {
1435
+ const query = new URLSearchParams({
1436
+ agentId: this.agentId
1437
+ });
1438
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1439
+ method: "POST",
1440
+ body: { messageIds }
1441
+ });
1442
+ }
956
1443
  };
957
1444
 
958
1445
  // src/resources/vector.ts
@@ -964,10 +1451,13 @@ var Vector = class extends BaseResource {
964
1451
  /**
965
1452
  * Retrieves details about a specific vector index
966
1453
  * @param indexName - Name of the index to get details for
1454
+ * @param runtimeContext - Optional runtime context to pass as query parameter
967
1455
  * @returns Promise containing vector index details
968
1456
  */
969
- details(indexName) {
970
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1457
+ details(indexName, runtimeContext) {
1458
+ return this.request(
1459
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1460
+ );
971
1461
  }
972
1462
  /**
973
1463
  * Deletes a vector index
@@ -981,10 +1471,11 @@ var Vector = class extends BaseResource {
981
1471
  }
982
1472
  /**
983
1473
  * Retrieves a list of all available indexes
1474
+ * @param runtimeContext - Optional runtime context to pass as query parameter
984
1475
  * @returns Promise containing array of index names
985
1476
  */
986
- getIndexes() {
987
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1477
+ getIndexes(runtimeContext) {
1478
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
988
1479
  }
989
1480
  /**
990
1481
  * Creates a new vector index
@@ -1021,227 +1512,47 @@ var Vector = class extends BaseResource {
1021
1512
  }
1022
1513
  };
1023
1514
 
1024
- // src/resources/legacy-workflow.ts
1025
- var RECORD_SEPARATOR = "";
1026
- var LegacyWorkflow = class extends BaseResource {
1027
- constructor(options, workflowId) {
1515
+ // src/resources/tool.ts
1516
+ var Tool = class extends BaseResource {
1517
+ constructor(options, toolId) {
1028
1518
  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}`);
1519
+ this.toolId = toolId;
1037
1520
  }
1038
1521
  /**
1039
- * Retrieves all runs for a legacy workflow
1040
- * @param params - Parameters for filtering runs
1041
- * @returns Promise containing legacy workflow runs array
1522
+ * Retrieves details about the tool
1523
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1524
+ * @returns Promise containing tool details including description and schemas
1042
1525
  */
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
- }
1526
+ details(runtimeContext) {
1527
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
1065
1528
  }
1066
1529
  /**
1067
- * Creates a new legacy workflow run
1068
- * @returns Promise containing the generated run ID
1530
+ * Executes the tool with the provided parameters
1531
+ * @param params - Parameters required for tool execution
1532
+ * @returns Promise containing the tool execution results
1069
1533
  */
1070
- createRun(params) {
1071
- const searchParams = new URLSearchParams();
1072
- if (!!params?.runId) {
1073
- searchParams.set("runId", params.runId);
1534
+ execute(params) {
1535
+ const url = new URLSearchParams();
1536
+ if (params.runId) {
1537
+ url.set("runId", params.runId);
1074
1538
  }
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}`, {
1539
+ const body = {
1540
+ data: params.data,
1541
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1542
+ };
1543
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1086
1544
  method: "POST",
1087
- body: params?.triggerData
1545
+ body
1088
1546
  });
1089
1547
  }
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
- // src/resources/tool.ts
1206
- var Tool2 = class extends BaseResource {
1207
- constructor(options, toolId) {
1208
- super(options);
1209
- this.toolId = toolId;
1210
- }
1211
- /**
1212
- * Retrieves details about the tool
1213
- * @returns Promise containing tool details including description and schemas
1214
- */
1215
- details() {
1216
- return this.request(`/api/tools/${this.toolId}`);
1217
- }
1218
- /**
1219
- * Executes the tool with the provided parameters
1220
- * @param params - Parameters required for tool execution
1221
- * @returns Promise containing the tool execution results
1222
- */
1223
- execute(params) {
1224
- const url = new URLSearchParams();
1225
- if (params.runId) {
1226
- url.set("runId", params.runId);
1227
- }
1228
- const body = {
1229
- data: params.data,
1230
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1231
- };
1232
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
1233
- method: "POST",
1234
- body
1235
- });
1236
- }
1237
- };
1238
-
1239
- // src/resources/workflow.ts
1240
- var RECORD_SEPARATOR2 = "";
1241
- var Workflow = class extends BaseResource {
1242
- constructor(options, workflowId) {
1243
- super(options);
1244
- this.workflowId = workflowId;
1548
+ };
1549
+
1550
+ // src/resources/workflow.ts
1551
+ var RECORD_SEPARATOR = "";
1552
+ var Workflow = class extends BaseResource {
1553
+ constructor(options, workflowId) {
1554
+ super(options);
1555
+ this.workflowId = workflowId;
1245
1556
  }
1246
1557
  /**
1247
1558
  * Creates an async generator that processes a readable stream and yields workflow records
@@ -1261,7 +1572,7 @@ var Workflow = class extends BaseResource {
1261
1572
  if (done && !value) continue;
1262
1573
  try {
1263
1574
  const decoded = value ? new TextDecoder().decode(value) : "";
1264
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1575
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
1265
1576
  buffer = chunks.pop() || "";
1266
1577
  for (const chunk of chunks) {
1267
1578
  if (chunk) {
@@ -1290,17 +1601,20 @@ var Workflow = class extends BaseResource {
1290
1601
  }
1291
1602
  /**
1292
1603
  * Retrieves details about the workflow
1604
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1293
1605
  * @returns Promise containing workflow details including steps and graphs
1294
1606
  */
1295
- details() {
1296
- return this.request(`/api/workflows/${this.workflowId}`);
1607
+ details(runtimeContext) {
1608
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
1297
1609
  }
1298
1610
  /**
1299
1611
  * Retrieves all runs for a workflow
1300
1612
  * @param params - Parameters for filtering runs
1613
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1301
1614
  * @returns Promise containing workflow runs array
1302
1615
  */
1303
- runs(params) {
1616
+ runs(params, runtimeContext) {
1617
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
1304
1618
  const searchParams = new URLSearchParams();
1305
1619
  if (params?.fromDate) {
1306
1620
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -1308,15 +1622,18 @@ var Workflow = class extends BaseResource {
1308
1622
  if (params?.toDate) {
1309
1623
  searchParams.set("toDate", params.toDate.toISOString());
1310
1624
  }
1311
- if (params?.limit) {
1625
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1312
1626
  searchParams.set("limit", String(params.limit));
1313
1627
  }
1314
- if (params?.offset) {
1628
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1315
1629
  searchParams.set("offset", String(params.offset));
1316
1630
  }
1317
1631
  if (params?.resourceId) {
1318
1632
  searchParams.set("resourceId", params.resourceId);
1319
1633
  }
1634
+ if (runtimeContextParam) {
1635
+ searchParams.set("runtimeContext", runtimeContextParam);
1636
+ }
1320
1637
  if (searchParams.size) {
1321
1638
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1322
1639
  } else {
@@ -1326,18 +1643,22 @@ var Workflow = class extends BaseResource {
1326
1643
  /**
1327
1644
  * Retrieves a specific workflow run by its ID
1328
1645
  * @param runId - The ID of the workflow run to retrieve
1646
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1329
1647
  * @returns Promise containing the workflow run details
1330
1648
  */
1331
- runById(runId) {
1332
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1649
+ runById(runId, runtimeContext) {
1650
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1333
1651
  }
1334
1652
  /**
1335
1653
  * Retrieves the execution result for a specific workflow run by its ID
1336
1654
  * @param runId - The ID of the workflow run to retrieve the execution result for
1655
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1337
1656
  * @returns Promise containing the workflow run execution result
1338
1657
  */
1339
- runExecutionResult(runId) {
1340
- return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1658
+ runExecutionResult(runId, runtimeContext) {
1659
+ return this.request(
1660
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1661
+ );
1341
1662
  }
1342
1663
  /**
1343
1664
  * Cancels a specific workflow run by its ID
@@ -1349,19 +1670,94 @@ var Workflow = class extends BaseResource {
1349
1670
  method: "POST"
1350
1671
  });
1351
1672
  }
1673
+ /**
1674
+ * Sends an event to a specific workflow run by its ID
1675
+ * @param params - Object containing the runId, event and data
1676
+ * @returns Promise containing a success message
1677
+ */
1678
+ sendRunEvent(params) {
1679
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1680
+ method: "POST",
1681
+ body: { event: params.event, data: params.data }
1682
+ });
1683
+ }
1684
+ /**
1685
+ * @deprecated Use createRunAsync() instead.
1686
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1687
+ */
1688
+ async createRun(_params) {
1689
+ throw new Error(
1690
+ "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."
1691
+ );
1692
+ }
1352
1693
  /**
1353
1694
  * Creates a new workflow run
1354
1695
  * @param params - Optional object containing the optional runId
1355
- * @returns Promise containing the runId of the created run
1696
+ * @returns Promise containing the runId of the created run with methods to control execution
1356
1697
  */
1357
- createRun(params) {
1698
+ async createRunAsync(params) {
1358
1699
  const searchParams = new URLSearchParams();
1359
1700
  if (!!params?.runId) {
1360
1701
  searchParams.set("runId", params.runId);
1361
1702
  }
1362
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1363
- method: "POST"
1364
- });
1703
+ const res = await this.request(
1704
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1705
+ {
1706
+ method: "POST"
1707
+ }
1708
+ );
1709
+ const runId = res.runId;
1710
+ return {
1711
+ runId,
1712
+ start: async (p) => {
1713
+ return this.start({
1714
+ runId,
1715
+ inputData: p.inputData,
1716
+ runtimeContext: p.runtimeContext,
1717
+ tracingOptions: p.tracingOptions
1718
+ });
1719
+ },
1720
+ startAsync: async (p) => {
1721
+ return this.startAsync({
1722
+ runId,
1723
+ inputData: p.inputData,
1724
+ runtimeContext: p.runtimeContext,
1725
+ tracingOptions: p.tracingOptions
1726
+ });
1727
+ },
1728
+ watch: async (onRecord) => {
1729
+ return this.watch({ runId }, onRecord);
1730
+ },
1731
+ stream: async (p) => {
1732
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1733
+ },
1734
+ resume: async (p) => {
1735
+ return this.resume({
1736
+ runId,
1737
+ step: p.step,
1738
+ resumeData: p.resumeData,
1739
+ runtimeContext: p.runtimeContext,
1740
+ tracingOptions: p.tracingOptions
1741
+ });
1742
+ },
1743
+ resumeAsync: async (p) => {
1744
+ return this.resumeAsync({
1745
+ runId,
1746
+ step: p.step,
1747
+ resumeData: p.resumeData,
1748
+ runtimeContext: p.runtimeContext,
1749
+ tracingOptions: p.tracingOptions
1750
+ });
1751
+ },
1752
+ resumeStreamVNext: async (p) => {
1753
+ return this.resumeStreamVNext({
1754
+ runId,
1755
+ step: p.step,
1756
+ resumeData: p.resumeData,
1757
+ runtimeContext: p.runtimeContext
1758
+ });
1759
+ }
1760
+ };
1365
1761
  }
1366
1762
  /**
1367
1763
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -1372,7 +1768,7 @@ var Workflow = class extends BaseResource {
1372
1768
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1373
1769
  return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1374
1770
  method: "POST",
1375
- body: { inputData: params?.inputData, runtimeContext }
1771
+ body: { inputData: params?.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1376
1772
  });
1377
1773
  }
1378
1774
  /**
@@ -1384,16 +1780,17 @@ var Workflow = class extends BaseResource {
1384
1780
  step,
1385
1781
  runId,
1386
1782
  resumeData,
1783
+ tracingOptions,
1387
1784
  ...rest
1388
1785
  }) {
1389
1786
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1390
1787
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1391
1788
  method: "POST",
1392
- stream: true,
1393
1789
  body: {
1394
1790
  step,
1395
1791
  resumeData,
1396
- runtimeContext
1792
+ runtimeContext,
1793
+ tracingOptions
1397
1794
  }
1398
1795
  });
1399
1796
  }
@@ -1410,7 +1807,7 @@ var Workflow = class extends BaseResource {
1410
1807
  const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1411
1808
  return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1412
1809
  method: "POST",
1413
- body: { inputData: params.inputData, runtimeContext }
1810
+ body: { inputData: params.inputData, runtimeContext, tracingOptions: params.tracingOptions }
1414
1811
  });
1415
1812
  }
1416
1813
  /**
@@ -1432,25 +1829,127 @@ var Workflow = class extends BaseResource {
1432
1829
  stream: true
1433
1830
  }
1434
1831
  );
1832
+ if (!response.ok) {
1833
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1834
+ }
1835
+ if (!response.body) {
1836
+ throw new Error("Response body is null");
1837
+ }
1838
+ let failedChunk = void 0;
1839
+ const transformStream = new TransformStream({
1840
+ start() {
1841
+ },
1842
+ async transform(chunk, controller) {
1843
+ try {
1844
+ const decoded = new TextDecoder().decode(chunk);
1845
+ const chunks = decoded.split(RECORD_SEPARATOR);
1846
+ for (const chunk2 of chunks) {
1847
+ if (chunk2) {
1848
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1849
+ try {
1850
+ const parsedChunk = JSON.parse(newChunk);
1851
+ controller.enqueue(parsedChunk);
1852
+ failedChunk = void 0;
1853
+ } catch {
1854
+ failedChunk = newChunk;
1855
+ }
1856
+ }
1857
+ }
1858
+ } catch {
1859
+ }
1860
+ }
1861
+ });
1862
+ return response.body.pipeThrough(transformStream);
1863
+ }
1864
+ /**
1865
+ * Observes workflow stream for a workflow run
1866
+ * @param params - Object containing the runId
1867
+ * @returns Promise containing the workflow execution results
1868
+ */
1869
+ async observeStream(params) {
1870
+ const searchParams = new URLSearchParams();
1871
+ searchParams.set("runId", params.runId);
1872
+ const response = await this.request(
1873
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1874
+ {
1875
+ method: "POST",
1876
+ stream: true
1877
+ }
1878
+ );
1879
+ if (!response.ok) {
1880
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1881
+ }
1882
+ if (!response.body) {
1883
+ throw new Error("Response body is null");
1884
+ }
1885
+ let failedChunk = void 0;
1886
+ const transformStream = new TransformStream({
1887
+ start() {
1888
+ },
1889
+ async transform(chunk, controller) {
1890
+ try {
1891
+ const decoded = new TextDecoder().decode(chunk);
1892
+ const chunks = decoded.split(RECORD_SEPARATOR);
1893
+ for (const chunk2 of chunks) {
1894
+ if (chunk2) {
1895
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1896
+ try {
1897
+ const parsedChunk = JSON.parse(newChunk);
1898
+ controller.enqueue(parsedChunk);
1899
+ failedChunk = void 0;
1900
+ } catch {
1901
+ failedChunk = newChunk;
1902
+ }
1903
+ }
1904
+ }
1905
+ } catch {
1906
+ }
1907
+ }
1908
+ });
1909
+ return response.body.pipeThrough(transformStream);
1910
+ }
1911
+ /**
1912
+ * Starts a workflow run and returns a stream
1913
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1914
+ * @returns Promise containing the workflow execution results
1915
+ */
1916
+ async streamVNext(params) {
1917
+ const searchParams = new URLSearchParams();
1918
+ if (!!params?.runId) {
1919
+ searchParams.set("runId", params.runId);
1920
+ }
1921
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1922
+ const response = await this.request(
1923
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1924
+ {
1925
+ method: "POST",
1926
+ body: { inputData: params.inputData, runtimeContext, closeOnSuspend: params.closeOnSuspend },
1927
+ stream: true
1928
+ }
1929
+ );
1435
1930
  if (!response.ok) {
1436
1931
  throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1437
1932
  }
1438
1933
  if (!response.body) {
1439
1934
  throw new Error("Response body is null");
1440
1935
  }
1936
+ let failedChunk = void 0;
1441
1937
  const transformStream = new TransformStream({
1442
1938
  start() {
1443
1939
  },
1444
1940
  async transform(chunk, controller) {
1445
1941
  try {
1446
1942
  const decoded = new TextDecoder().decode(chunk);
1447
- const chunks = decoded.split(RECORD_SEPARATOR2);
1943
+ const chunks = decoded.split(RECORD_SEPARATOR);
1448
1944
  for (const chunk2 of chunks) {
1449
1945
  if (chunk2) {
1946
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1450
1947
  try {
1451
- const parsedChunk = JSON.parse(chunk2);
1948
+ const parsedChunk = JSON.parse(newChunk);
1452
1949
  controller.enqueue(parsedChunk);
1950
+ failedChunk = void 0;
1453
1951
  } catch {
1952
+ failedChunk = newChunk;
1454
1953
  }
1455
1954
  }
1456
1955
  }
@@ -1472,7 +1971,25 @@ var Workflow = class extends BaseResource {
1472
1971
  body: {
1473
1972
  step: params.step,
1474
1973
  resumeData: params.resumeData,
1475
- runtimeContext
1974
+ runtimeContext,
1975
+ tracingOptions: params.tracingOptions
1976
+ }
1977
+ });
1978
+ }
1979
+ /**
1980
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
1981
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1982
+ * @returns Promise containing the workflow resume results
1983
+ */
1984
+ resumeStreamVNext(params) {
1985
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1986
+ return this.request(`/api/workflows/${this.workflowId}/resume-stream?runId=${params.runId}`, {
1987
+ method: "POST",
1988
+ body: {
1989
+ step: params.step,
1990
+ resumeData: params.resumeData,
1991
+ runtimeContext,
1992
+ tracingOptions: params.tracingOptions
1476
1993
  }
1477
1994
  });
1478
1995
  }
@@ -1512,7 +2029,7 @@ var Workflow = class extends BaseResource {
1512
2029
  async start(controller) {
1513
2030
  try {
1514
2031
  for await (const record of records) {
1515
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
2032
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
1516
2033
  controller.enqueue(encoder.encode(json));
1517
2034
  }
1518
2035
  controller.close();
@@ -1535,99 +2052,609 @@ var A2A = class extends BaseResource {
1535
2052
  * @returns Promise containing the agent card information
1536
2053
  */
1537
2054
  async getCard() {
1538
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2055
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1539
2056
  }
1540
2057
  /**
1541
- * Send a message to the agent and get a response
2058
+ * Send a message to the agent and gets a message or task response
1542
2059
  * @param params - Parameters for the task
1543
- * @returns Promise containing the task response
2060
+ * @returns Promise containing the response
1544
2061
  */
1545
2062
  async sendMessage(params) {
1546
2063
  const response = await this.request(`/a2a/${this.agentId}`, {
1547
2064
  method: "POST",
1548
- body: {
1549
- method: "tasks/send",
1550
- params
1551
- }
2065
+ body: {
2066
+ method: "message/send",
2067
+ params
2068
+ }
2069
+ });
2070
+ return response;
2071
+ }
2072
+ /**
2073
+ * Sends a message to an agent to initiate/continue a task and subscribes
2074
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2075
+ * @param params - Parameters for the task
2076
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2077
+ */
2078
+ async sendStreamingMessage(params) {
2079
+ const response = await this.request(`/a2a/${this.agentId}`, {
2080
+ method: "POST",
2081
+ body: {
2082
+ method: "message/stream",
2083
+ params
2084
+ }
2085
+ });
2086
+ return response;
2087
+ }
2088
+ /**
2089
+ * Get the status and result of a task
2090
+ * @param params - Parameters for querying the task
2091
+ * @returns Promise containing the task response
2092
+ */
2093
+ async getTask(params) {
2094
+ const response = await this.request(`/a2a/${this.agentId}`, {
2095
+ method: "POST",
2096
+ body: {
2097
+ method: "tasks/get",
2098
+ params
2099
+ }
2100
+ });
2101
+ return response;
2102
+ }
2103
+ /**
2104
+ * Cancel a running task
2105
+ * @param params - Parameters identifying the task to cancel
2106
+ * @returns Promise containing the task response
2107
+ */
2108
+ async cancelTask(params) {
2109
+ return this.request(`/a2a/${this.agentId}`, {
2110
+ method: "POST",
2111
+ body: {
2112
+ method: "tasks/cancel",
2113
+ params
2114
+ }
2115
+ });
2116
+ }
2117
+ };
2118
+
2119
+ // src/resources/mcp-tool.ts
2120
+ var MCPTool = class extends BaseResource {
2121
+ serverId;
2122
+ toolId;
2123
+ constructor(options, serverId, toolId) {
2124
+ super(options);
2125
+ this.serverId = serverId;
2126
+ this.toolId = toolId;
2127
+ }
2128
+ /**
2129
+ * Retrieves details about this specific tool from the MCP server.
2130
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2131
+ * @returns Promise containing the tool's information (name, description, schema).
2132
+ */
2133
+ details(runtimeContext) {
2134
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2135
+ }
2136
+ /**
2137
+ * Executes this specific tool on the MCP server.
2138
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2139
+ * @returns Promise containing the result of the tool execution.
2140
+ */
2141
+ execute(params) {
2142
+ const body = {};
2143
+ if (params.data !== void 0) body.data = params.data;
2144
+ if (params.runtimeContext !== void 0) {
2145
+ body.runtimeContext = params.runtimeContext;
2146
+ }
2147
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2148
+ method: "POST",
2149
+ body: Object.keys(body).length > 0 ? body : void 0
2150
+ });
2151
+ }
2152
+ };
2153
+
2154
+ // src/resources/agent-builder.ts
2155
+ var RECORD_SEPARATOR2 = "";
2156
+ var AgentBuilder = class extends BaseResource {
2157
+ constructor(options, actionId) {
2158
+ super(options);
2159
+ this.actionId = actionId;
2160
+ }
2161
+ // Helper function to transform workflow result to action result
2162
+ transformWorkflowResult(result) {
2163
+ if (result.status === "success") {
2164
+ return {
2165
+ success: result.result.success || false,
2166
+ applied: result.result.applied || false,
2167
+ branchName: result.result.branchName,
2168
+ message: result.result.message || "Agent builder action completed",
2169
+ validationResults: result.result.validationResults,
2170
+ error: result.result.error,
2171
+ errors: result.result.errors,
2172
+ stepResults: result.result.stepResults
2173
+ };
2174
+ } else if (result.status === "failed") {
2175
+ return {
2176
+ success: false,
2177
+ applied: false,
2178
+ message: `Agent builder action failed: ${result.error.message}`,
2179
+ error: result.error.message
2180
+ };
2181
+ } else {
2182
+ return {
2183
+ success: false,
2184
+ applied: false,
2185
+ message: "Agent builder action was suspended",
2186
+ error: "Workflow suspended - manual intervention required"
2187
+ };
2188
+ }
2189
+ }
2190
+ /**
2191
+ * @deprecated Use createRunAsync() instead.
2192
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2193
+ */
2194
+ async createRun(_params) {
2195
+ throw new Error(
2196
+ "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."
2197
+ );
2198
+ }
2199
+ /**
2200
+ * Creates a new agent builder action run and returns the runId.
2201
+ * This calls `/api/agent-builder/:actionId/create-run`.
2202
+ */
2203
+ async createRunAsync(params) {
2204
+ const searchParams = new URLSearchParams();
2205
+ if (!!params?.runId) {
2206
+ searchParams.set("runId", params.runId);
2207
+ }
2208
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2209
+ return this.request(url, {
2210
+ method: "POST"
2211
+ });
2212
+ }
2213
+ /**
2214
+ * Starts agent builder action asynchronously and waits for completion.
2215
+ * This calls `/api/agent-builder/:actionId/start-async`.
2216
+ */
2217
+ async startAsync(params, runId) {
2218
+ const searchParams = new URLSearchParams();
2219
+ if (runId) {
2220
+ searchParams.set("runId", runId);
2221
+ }
2222
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2223
+ const { runtimeContext: _, ...actionParams } = params;
2224
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2225
+ const result = await this.request(url, {
2226
+ method: "POST",
2227
+ body: { ...actionParams, runtimeContext }
2228
+ });
2229
+ return this.transformWorkflowResult(result);
2230
+ }
2231
+ /**
2232
+ * Starts an existing agent builder action run.
2233
+ * This calls `/api/agent-builder/:actionId/start`.
2234
+ */
2235
+ async startActionRun(params, runId) {
2236
+ const searchParams = new URLSearchParams();
2237
+ searchParams.set("runId", runId);
2238
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2239
+ const { runtimeContext: _, ...actionParams } = params;
2240
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2241
+ return this.request(url, {
2242
+ method: "POST",
2243
+ body: { ...actionParams, runtimeContext }
2244
+ });
2245
+ }
2246
+ /**
2247
+ * Resumes a suspended agent builder action step.
2248
+ * This calls `/api/agent-builder/:actionId/resume`.
2249
+ */
2250
+ async resume(params, runId) {
2251
+ const searchParams = new URLSearchParams();
2252
+ searchParams.set("runId", runId);
2253
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2254
+ const { runtimeContext: _, ...resumeParams } = params;
2255
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2256
+ return this.request(url, {
2257
+ method: "POST",
2258
+ body: { ...resumeParams, runtimeContext }
2259
+ });
2260
+ }
2261
+ /**
2262
+ * Resumes a suspended agent builder action step asynchronously.
2263
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2264
+ */
2265
+ async resumeAsync(params, runId) {
2266
+ const searchParams = new URLSearchParams();
2267
+ searchParams.set("runId", runId);
2268
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2269
+ const { runtimeContext: _, ...resumeParams } = params;
2270
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2271
+ const result = await this.request(url, {
2272
+ method: "POST",
2273
+ body: { ...resumeParams, runtimeContext }
2274
+ });
2275
+ return this.transformWorkflowResult(result);
2276
+ }
2277
+ /**
2278
+ * Creates an async generator that processes a readable stream and yields action records
2279
+ * separated by the Record Separator character (\x1E)
2280
+ *
2281
+ * @param stream - The readable stream to process
2282
+ * @returns An async generator that yields parsed records
2283
+ */
2284
+ async *streamProcessor(stream) {
2285
+ const reader = stream.getReader();
2286
+ let doneReading = false;
2287
+ let buffer = "";
2288
+ try {
2289
+ while (!doneReading) {
2290
+ const { done, value } = await reader.read();
2291
+ doneReading = done;
2292
+ if (done && !value) continue;
2293
+ try {
2294
+ const decoded = value ? new TextDecoder().decode(value) : "";
2295
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2296
+ buffer = chunks.pop() || "";
2297
+ for (const chunk of chunks) {
2298
+ if (chunk) {
2299
+ if (typeof chunk === "string") {
2300
+ try {
2301
+ const parsedChunk = JSON.parse(chunk);
2302
+ yield parsedChunk;
2303
+ } catch {
2304
+ }
2305
+ }
2306
+ }
2307
+ }
2308
+ } catch {
2309
+ }
2310
+ }
2311
+ if (buffer) {
2312
+ try {
2313
+ yield JSON.parse(buffer);
2314
+ } catch {
2315
+ }
2316
+ }
2317
+ } finally {
2318
+ reader.cancel().catch(() => {
2319
+ });
2320
+ }
2321
+ }
2322
+ /**
2323
+ * Streams agent builder action progress in real-time.
2324
+ * This calls `/api/agent-builder/:actionId/stream`.
2325
+ */
2326
+ async stream(params, runId) {
2327
+ const searchParams = new URLSearchParams();
2328
+ if (runId) {
2329
+ searchParams.set("runId", runId);
2330
+ }
2331
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2332
+ const { runtimeContext: _, ...actionParams } = params;
2333
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2334
+ const response = await this.request(url, {
2335
+ method: "POST",
2336
+ body: { ...actionParams, runtimeContext },
2337
+ stream: true
2338
+ });
2339
+ if (!response.ok) {
2340
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2341
+ }
2342
+ if (!response.body) {
2343
+ throw new Error("Response body is null");
2344
+ }
2345
+ let failedChunk = void 0;
2346
+ const transformStream = new TransformStream({
2347
+ start() {
2348
+ },
2349
+ async transform(chunk, controller) {
2350
+ try {
2351
+ const decoded = new TextDecoder().decode(chunk);
2352
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2353
+ for (const chunk2 of chunks) {
2354
+ if (chunk2) {
2355
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2356
+ try {
2357
+ const parsedChunk = JSON.parse(newChunk);
2358
+ controller.enqueue(parsedChunk);
2359
+ failedChunk = void 0;
2360
+ } catch {
2361
+ failedChunk = newChunk;
2362
+ }
2363
+ }
2364
+ }
2365
+ } catch {
2366
+ }
2367
+ }
2368
+ });
2369
+ return response.body.pipeThrough(transformStream);
2370
+ }
2371
+ /**
2372
+ * Streams agent builder action progress in real-time using VNext streaming.
2373
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2374
+ */
2375
+ async streamVNext(params, runId) {
2376
+ const searchParams = new URLSearchParams();
2377
+ if (runId) {
2378
+ searchParams.set("runId", runId);
2379
+ }
2380
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2381
+ const { runtimeContext: _, ...actionParams } = params;
2382
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2383
+ const response = await this.request(url, {
2384
+ method: "POST",
2385
+ body: { ...actionParams, runtimeContext },
2386
+ stream: true
2387
+ });
2388
+ if (!response.ok) {
2389
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2390
+ }
2391
+ if (!response.body) {
2392
+ throw new Error("Response body is null");
2393
+ }
2394
+ let failedChunk = void 0;
2395
+ const transformStream = new TransformStream({
2396
+ start() {
2397
+ },
2398
+ async transform(chunk, controller) {
2399
+ try {
2400
+ const decoded = new TextDecoder().decode(chunk);
2401
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2402
+ for (const chunk2 of chunks) {
2403
+ if (chunk2) {
2404
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2405
+ try {
2406
+ const parsedChunk = JSON.parse(newChunk);
2407
+ controller.enqueue(parsedChunk);
2408
+ failedChunk = void 0;
2409
+ } catch {
2410
+ failedChunk = newChunk;
2411
+ }
2412
+ }
2413
+ }
2414
+ } catch {
2415
+ }
2416
+ }
2417
+ });
2418
+ return response.body.pipeThrough(transformStream);
2419
+ }
2420
+ /**
2421
+ * Watches an existing agent builder action run by runId.
2422
+ * This is used for hot reload recovery - it loads the existing run state
2423
+ * and streams any remaining progress.
2424
+ * This calls `/api/agent-builder/:actionId/watch`.
2425
+ */
2426
+ async watch({ runId, eventType }, onRecord) {
2427
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2428
+ const response = await this.request(url, {
2429
+ method: "GET",
2430
+ stream: true
2431
+ });
2432
+ if (!response.ok) {
2433
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2434
+ }
2435
+ if (!response.body) {
2436
+ throw new Error("Response body is null");
2437
+ }
2438
+ for await (const record of this.streamProcessor(response.body)) {
2439
+ if (typeof record === "string") {
2440
+ onRecord(JSON.parse(record));
2441
+ } else {
2442
+ onRecord(record);
2443
+ }
2444
+ }
2445
+ }
2446
+ /**
2447
+ * Gets a specific action run by its ID.
2448
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2449
+ */
2450
+ async runById(runId) {
2451
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2452
+ return this.request(url, {
2453
+ method: "GET"
2454
+ });
2455
+ }
2456
+ /**
2457
+ * Gets details about this agent builder action.
2458
+ * This calls `/api/agent-builder/:actionId`.
2459
+ */
2460
+ async details() {
2461
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2462
+ return result;
2463
+ }
2464
+ /**
2465
+ * Gets all runs for this agent builder action.
2466
+ * This calls `/api/agent-builder/:actionId/runs`.
2467
+ */
2468
+ async runs(params) {
2469
+ const searchParams = new URLSearchParams();
2470
+ if (params?.fromDate) {
2471
+ searchParams.set("fromDate", params.fromDate.toISOString());
2472
+ }
2473
+ if (params?.toDate) {
2474
+ searchParams.set("toDate", params.toDate.toISOString());
2475
+ }
2476
+ if (params?.limit !== void 0) {
2477
+ searchParams.set("limit", String(params.limit));
2478
+ }
2479
+ if (params?.offset !== void 0) {
2480
+ searchParams.set("offset", String(params.offset));
2481
+ }
2482
+ if (params?.resourceId) {
2483
+ searchParams.set("resourceId", params.resourceId);
2484
+ }
2485
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2486
+ return this.request(url, {
2487
+ method: "GET"
2488
+ });
2489
+ }
2490
+ /**
2491
+ * Gets the execution result of an agent builder action run.
2492
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2493
+ */
2494
+ async runExecutionResult(runId) {
2495
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2496
+ return this.request(url, {
2497
+ method: "GET"
2498
+ });
2499
+ }
2500
+ /**
2501
+ * Cancels an agent builder action run.
2502
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2503
+ */
2504
+ async cancelRun(runId) {
2505
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2506
+ return this.request(url, {
2507
+ method: "POST"
2508
+ });
2509
+ }
2510
+ /**
2511
+ * Sends an event to an agent builder action run.
2512
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2513
+ */
2514
+ async sendRunEvent(params) {
2515
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2516
+ return this.request(url, {
2517
+ method: "POST",
2518
+ body: { event: params.event, data: params.data }
2519
+ });
2520
+ }
2521
+ };
2522
+
2523
+ // src/resources/observability.ts
2524
+ var Observability = class extends BaseResource {
2525
+ constructor(options) {
2526
+ super(options);
2527
+ }
2528
+ /**
2529
+ * Retrieves a specific AI trace by ID
2530
+ * @param traceId - ID of the trace to retrieve
2531
+ * @returns Promise containing the AI trace with all its spans
2532
+ */
2533
+ getTrace(traceId) {
2534
+ return this.request(`/api/observability/traces/${traceId}`);
2535
+ }
2536
+ /**
2537
+ * Retrieves paginated list of AI traces with optional filtering
2538
+ * @param params - Parameters for pagination and filtering
2539
+ * @returns Promise containing paginated traces and pagination info
2540
+ */
2541
+ getTraces(params) {
2542
+ const { pagination, filters } = params;
2543
+ const { page, perPage, dateRange } = pagination || {};
2544
+ const { name, spanType, entityId, entityType } = filters || {};
2545
+ const searchParams = new URLSearchParams();
2546
+ if (page !== void 0) {
2547
+ searchParams.set("page", String(page));
2548
+ }
2549
+ if (perPage !== void 0) {
2550
+ searchParams.set("perPage", String(perPage));
2551
+ }
2552
+ if (name) {
2553
+ searchParams.set("name", name);
2554
+ }
2555
+ if (spanType !== void 0) {
2556
+ searchParams.set("spanType", String(spanType));
2557
+ }
2558
+ if (entityId && entityType) {
2559
+ searchParams.set("entityId", entityId);
2560
+ searchParams.set("entityType", entityType);
2561
+ }
2562
+ if (dateRange) {
2563
+ const dateRangeStr = JSON.stringify({
2564
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2565
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2566
+ });
2567
+ searchParams.set("dateRange", dateRangeStr);
2568
+ }
2569
+ const queryString = searchParams.toString();
2570
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2571
+ }
2572
+ /**
2573
+ * Retrieves scores by trace ID and span ID
2574
+ * @param params - Parameters containing trace ID, span ID, and pagination options
2575
+ * @returns Promise containing scores and pagination info
2576
+ */
2577
+ getScoresBySpan(params) {
2578
+ const { traceId, spanId, page, perPage } = params;
2579
+ const searchParams = new URLSearchParams();
2580
+ if (page !== void 0) {
2581
+ searchParams.set("page", String(page));
2582
+ }
2583
+ if (perPage !== void 0) {
2584
+ searchParams.set("perPage", String(perPage));
2585
+ }
2586
+ const queryString = searchParams.toString();
2587
+ return this.request(
2588
+ `/api/observability/traces/${encodeURIComponent(traceId)}/${encodeURIComponent(spanId)}/scores${queryString ? `?${queryString}` : ""}`
2589
+ );
2590
+ }
2591
+ score(params) {
2592
+ return this.request(`/api/observability/traces/score`, {
2593
+ method: "POST",
2594
+ body: { ...params }
1552
2595
  });
1553
- return { task: response.result };
2596
+ }
2597
+ };
2598
+
2599
+ // src/resources/network-memory-thread.ts
2600
+ var NetworkMemoryThread = class extends BaseResource {
2601
+ constructor(options, threadId, networkId) {
2602
+ super(options);
2603
+ this.threadId = threadId;
2604
+ this.networkId = networkId;
1554
2605
  }
1555
2606
  /**
1556
- * Get the status and result of a task
1557
- * @param params - Parameters for querying the task
1558
- * @returns Promise containing the task response
2607
+ * Retrieves the memory thread details
2608
+ * @returns Promise containing thread details including title and metadata
1559
2609
  */
1560
- async getTask(params) {
1561
- const response = await this.request(`/a2a/${this.agentId}`, {
1562
- method: "POST",
1563
- body: {
1564
- method: "tasks/get",
1565
- params
1566
- }
1567
- });
1568
- return response.result;
2610
+ get() {
2611
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1569
2612
  }
1570
2613
  /**
1571
- * Cancel a running task
1572
- * @param params - Parameters identifying the task to cancel
1573
- * @returns Promise containing the task response
2614
+ * Updates the memory thread properties
2615
+ * @param params - Update parameters including title and metadata
2616
+ * @returns Promise containing updated thread details
1574
2617
  */
1575
- async cancelTask(params) {
1576
- return this.request(`/a2a/${this.agentId}`, {
1577
- method: "POST",
1578
- body: {
1579
- method: "tasks/cancel",
1580
- params
1581
- }
2618
+ update(params) {
2619
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2620
+ method: "PATCH",
2621
+ body: params
1582
2622
  });
1583
2623
  }
1584
2624
  /**
1585
- * Send a message and subscribe to streaming updates (not fully implemented)
1586
- * @param params - Parameters for the task
1587
- * @returns Promise containing the task response
2625
+ * Deletes the memory thread
2626
+ * @returns Promise containing deletion result
1588
2627
  */
1589
- async sendAndSubscribe(params) {
1590
- return this.request(`/a2a/${this.agentId}`, {
1591
- method: "POST",
1592
- body: {
1593
- method: "tasks/sendSubscribe",
1594
- params
1595
- },
1596
- stream: true
2628
+ delete() {
2629
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2630
+ method: "DELETE"
1597
2631
  });
1598
2632
  }
1599
- };
1600
-
1601
- // src/resources/mcp-tool.ts
1602
- var MCPTool = class extends BaseResource {
1603
- serverId;
1604
- toolId;
1605
- constructor(options, serverId, toolId) {
1606
- super(options);
1607
- this.serverId = serverId;
1608
- this.toolId = toolId;
1609
- }
1610
2633
  /**
1611
- * Retrieves details about this specific tool from the MCP server.
1612
- * @returns Promise containing the tool's information (name, description, schema).
2634
+ * Retrieves messages associated with the thread
2635
+ * @param params - Optional parameters including limit for number of messages to retrieve
2636
+ * @returns Promise containing thread messages and UI messages
1613
2637
  */
1614
- details() {
1615
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
2638
+ getMessages(params) {
2639
+ const query = new URLSearchParams({
2640
+ networkId: this.networkId,
2641
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2642
+ });
2643
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1616
2644
  }
1617
2645
  /**
1618
- * Executes this specific tool on the MCP server.
1619
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1620
- * @returns Promise containing the result of the tool execution.
2646
+ * Deletes one or more messages from the thread
2647
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2648
+ * message object with id property, or array of message objects
2649
+ * @returns Promise containing deletion result
1621
2650
  */
1622
- execute(params) {
1623
- const body = {};
1624
- if (params.data !== void 0) body.data = params.data;
1625
- if (params.runtimeContext !== void 0) {
1626
- body.runtimeContext = params.runtimeContext;
1627
- }
1628
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2651
+ deleteMessages(messageIds) {
2652
+ const query = new URLSearchParams({
2653
+ networkId: this.networkId
2654
+ });
2655
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1629
2656
  method: "POST",
1630
- body: Object.keys(body).length > 0 ? body : void 0
2657
+ body: { messageIds }
1631
2658
  });
1632
2659
  }
1633
2660
  };
@@ -1641,10 +2668,11 @@ var VNextNetwork = class extends BaseResource {
1641
2668
  }
1642
2669
  /**
1643
2670
  * Retrieves details about the network
2671
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1644
2672
  * @returns Promise containing vNext network details
1645
2673
  */
1646
- details() {
1647
- return this.request(`/api/networks/v-next/${this.networkId}`);
2674
+ details(runtimeContext) {
2675
+ return this.request(`/api/networks/v-next/${this.networkId}${runtimeContextQueryString(runtimeContext)}`);
1648
2676
  }
1649
2677
  /**
1650
2678
  * Generates a response from the v-next network
@@ -1654,7 +2682,10 @@ var VNextNetwork = class extends BaseResource {
1654
2682
  generate(params) {
1655
2683
  return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1656
2684
  method: "POST",
1657
- body: params
2685
+ body: {
2686
+ ...params,
2687
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2688
+ }
1658
2689
  });
1659
2690
  }
1660
2691
  /**
@@ -1665,7 +2696,10 @@ var VNextNetwork = class extends BaseResource {
1665
2696
  loop(params) {
1666
2697
  return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1667
2698
  method: "POST",
1668
- body: params
2699
+ body: {
2700
+ ...params,
2701
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2702
+ }
1669
2703
  });
1670
2704
  }
1671
2705
  async *streamProcessor(stream) {
@@ -1714,7 +2748,10 @@ var VNextNetwork = class extends BaseResource {
1714
2748
  async stream(params, onRecord) {
1715
2749
  const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1716
2750
  method: "POST",
1717
- body: params,
2751
+ body: {
2752
+ ...params,
2753
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2754
+ },
1718
2755
  stream: true
1719
2756
  });
1720
2757
  if (!response.ok) {
@@ -1739,7 +2776,10 @@ var VNextNetwork = class extends BaseResource {
1739
2776
  async loopStream(params, onRecord) {
1740
2777
  const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1741
2778
  method: "POST",
1742
- body: params,
2779
+ body: {
2780
+ ...params,
2781
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2782
+ },
1743
2783
  stream: true
1744
2784
  });
1745
2785
  if (!response.ok) {
@@ -1758,80 +2798,26 @@ var VNextNetwork = class extends BaseResource {
1758
2798
  }
1759
2799
  };
1760
2800
 
1761
- // src/resources/network-memory-thread.ts
1762
- var NetworkMemoryThread = class extends BaseResource {
1763
- constructor(options, threadId, networkId) {
1764
- super(options);
1765
- this.threadId = threadId;
1766
- this.networkId = networkId;
1767
- }
1768
- /**
1769
- * Retrieves the memory thread details
1770
- * @returns Promise containing thread details including title and metadata
1771
- */
1772
- get() {
1773
- return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1774
- }
1775
- /**
1776
- * Updates the memory thread properties
1777
- * @param params - Update parameters including title and metadata
1778
- * @returns Promise containing updated thread details
1779
- */
1780
- update(params) {
1781
- return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1782
- method: "PATCH",
1783
- body: params
1784
- });
1785
- }
1786
- /**
1787
- * Deletes the memory thread
1788
- * @returns Promise containing deletion result
1789
- */
1790
- delete() {
1791
- return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1792
- method: "DELETE"
1793
- });
1794
- }
1795
- /**
1796
- * Retrieves messages associated with the thread
1797
- * @param params - Optional parameters including limit for number of messages to retrieve
1798
- * @returns Promise containing thread messages and UI messages
1799
- */
1800
- getMessages(params) {
1801
- const query = new URLSearchParams({
1802
- networkId: this.networkId,
1803
- ...params?.limit ? { limit: params.limit.toString() } : {}
1804
- });
1805
- return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1806
- }
1807
- };
1808
-
1809
2801
  // src/client.ts
1810
2802
  var MastraClient = class extends BaseResource {
2803
+ observability;
1811
2804
  constructor(options) {
1812
2805
  super(options);
2806
+ this.observability = new Observability(options);
1813
2807
  }
1814
2808
  /**
1815
2809
  * Retrieves all available agents
2810
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1816
2811
  * @returns Promise containing map of agent IDs to agent details
1817
2812
  */
1818
- getAgents() {
1819
- return this.request("/api/agents");
1820
- }
1821
- async getAGUI({ resourceId }) {
1822
- const agents = await this.getAgents();
1823
- return Object.entries(agents).reduce(
1824
- (acc, [agentId]) => {
1825
- const agent = this.getAgent(agentId);
1826
- acc[agentId] = new AGUIAdapter({
1827
- agentId,
1828
- agent,
1829
- resourceId
1830
- });
1831
- return acc;
1832
- },
1833
- {}
1834
- );
2813
+ getAgents(runtimeContext) {
2814
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2815
+ const searchParams = new URLSearchParams();
2816
+ if (runtimeContextParam) {
2817
+ searchParams.set("runtimeContext", runtimeContextParam);
2818
+ }
2819
+ const queryString = searchParams.toString();
2820
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
1835
2821
  }
1836
2822
  /**
1837
2823
  * Gets an agent instance by ID
@@ -1849,6 +2835,14 @@ var MastraClient = class extends BaseResource {
1849
2835
  getMemoryThreads(params) {
1850
2836
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1851
2837
  }
2838
+ /**
2839
+ * Retrieves memory config for a resource
2840
+ * @param params - Parameters containing the resource ID
2841
+ * @returns Promise containing array of memory threads
2842
+ */
2843
+ getMemoryConfig(params) {
2844
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2845
+ }
1852
2846
  /**
1853
2847
  * Creates a new memory thread
1854
2848
  * @param params - Parameters for creating the memory thread
@@ -1865,6 +2859,24 @@ var MastraClient = class extends BaseResource {
1865
2859
  getMemoryThread(threadId, agentId) {
1866
2860
  return new MemoryThread(this.options, threadId, agentId);
1867
2861
  }
2862
+ getThreadMessages(threadId, opts = {}) {
2863
+ let url = "";
2864
+ if (opts.agentId) {
2865
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2866
+ } else if (opts.networkId) {
2867
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2868
+ }
2869
+ return this.request(url);
2870
+ }
2871
+ deleteThread(threadId, opts = {}) {
2872
+ let url = "";
2873
+ if (opts.agentId) {
2874
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2875
+ } else if (opts.networkId) {
2876
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2877
+ }
2878
+ return this.request(url, { method: "DELETE" });
2879
+ }
1868
2880
  /**
1869
2881
  * Saves messages to memory
1870
2882
  * @param params - Parameters containing messages to save
@@ -1927,10 +2939,17 @@ var MastraClient = class extends BaseResource {
1927
2939
  }
1928
2940
  /**
1929
2941
  * Retrieves all available tools
2942
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1930
2943
  * @returns Promise containing map of tool IDs to tool details
1931
2944
  */
1932
- getTools() {
1933
- return this.request("/api/tools");
2945
+ getTools(runtimeContext) {
2946
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2947
+ const searchParams = new URLSearchParams();
2948
+ if (runtimeContextParam) {
2949
+ searchParams.set("runtimeContext", runtimeContextParam);
2950
+ }
2951
+ const queryString = searchParams.toString();
2952
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
1934
2953
  }
1935
2954
  /**
1936
2955
  * Gets a tool instance by ID
@@ -1938,29 +2957,21 @@ var MastraClient = class extends BaseResource {
1938
2957
  * @returns Tool instance
1939
2958
  */
1940
2959
  getTool(toolId) {
1941
- return new Tool2(this.options, toolId);
1942
- }
1943
- /**
1944
- * Retrieves all available legacy workflows
1945
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1946
- */
1947
- getLegacyWorkflows() {
1948
- return this.request("/api/workflows/legacy");
1949
- }
1950
- /**
1951
- * Gets a legacy workflow instance by ID
1952
- * @param workflowId - ID of the legacy workflow to retrieve
1953
- * @returns Legacy Workflow instance
1954
- */
1955
- getLegacyWorkflow(workflowId) {
1956
- return new LegacyWorkflow(this.options, workflowId);
2960
+ return new Tool(this.options, toolId);
1957
2961
  }
1958
2962
  /**
1959
2963
  * Retrieves all available workflows
2964
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1960
2965
  * @returns Promise containing map of workflow IDs to workflow details
1961
2966
  */
1962
- getWorkflows() {
1963
- return this.request("/api/workflows");
2967
+ getWorkflows(runtimeContext) {
2968
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2969
+ const searchParams = new URLSearchParams();
2970
+ if (runtimeContextParam) {
2971
+ searchParams.set("runtimeContext", runtimeContextParam);
2972
+ }
2973
+ const queryString = searchParams.toString();
2974
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
1964
2975
  }
1965
2976
  /**
1966
2977
  * Gets a workflow instance by ID
@@ -1970,6 +2981,20 @@ var MastraClient = class extends BaseResource {
1970
2981
  getWorkflow(workflowId) {
1971
2982
  return new Workflow(this.options, workflowId);
1972
2983
  }
2984
+ /**
2985
+ * Gets all available agent builder actions
2986
+ * @returns Promise containing map of action IDs to action details
2987
+ */
2988
+ getAgentBuilderActions() {
2989
+ return this.request("/api/agent-builder/");
2990
+ }
2991
+ /**
2992
+ * Gets an agent builder instance for executing agent-builder workflows
2993
+ * @returns AgentBuilder instance
2994
+ */
2995
+ getAgentBuilderAction(actionId) {
2996
+ return new AgentBuilder(this.options, actionId);
2997
+ }
1973
2998
  /**
1974
2999
  * Gets a vector instance by name
1975
3000
  * @param vectorName - Name of the vector to retrieve
@@ -2114,13 +3139,6 @@ var MastraClient = class extends BaseResource {
2114
3139
  return this.request(`/api/telemetry`);
2115
3140
  }
2116
3141
  }
2117
- /**
2118
- * Retrieves all available networks
2119
- * @returns Promise containing map of network IDs to network details
2120
- */
2121
- getNetworks() {
2122
- return this.request("/api/networks");
2123
- }
2124
3142
  /**
2125
3143
  * Retrieves all available vNext networks
2126
3144
  * @returns Promise containing map of vNext network IDs to vNext network details
@@ -2128,14 +3146,6 @@ var MastraClient = class extends BaseResource {
2128
3146
  getVNextNetworks() {
2129
3147
  return this.request("/api/networks/v-next");
2130
3148
  }
2131
- /**
2132
- * Gets a network instance by ID
2133
- * @param networkId - ID of the network to retrieve
2134
- * @returns Network instance
2135
- */
2136
- getNetwork(networkId) {
2137
- return new Network(this.options, networkId);
2138
- }
2139
3149
  /**
2140
3150
  * Gets a vNext network instance by ID
2141
3151
  * @param networkId - ID of the vNext network to retrieve
@@ -2200,6 +3210,163 @@ var MastraClient = class extends BaseResource {
2200
3210
  getA2A(agentId) {
2201
3211
  return new A2A(this.options, agentId);
2202
3212
  }
3213
+ /**
3214
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3215
+ * @param agentId - ID of the agent.
3216
+ * @param threadId - ID of the thread.
3217
+ * @param resourceId - Optional ID of the resource.
3218
+ * @returns Working memory for the specified thread or resource.
3219
+ */
3220
+ getWorkingMemory({
3221
+ agentId,
3222
+ threadId,
3223
+ resourceId
3224
+ }) {
3225
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3226
+ }
3227
+ /**
3228
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3229
+ * @param agentId - ID of the agent.
3230
+ * @param threadId - ID of the thread.
3231
+ * @param workingMemory - The new working memory content.
3232
+ * @param resourceId - Optional ID of the resource.
3233
+ */
3234
+ updateWorkingMemory({
3235
+ agentId,
3236
+ threadId,
3237
+ workingMemory,
3238
+ resourceId
3239
+ }) {
3240
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3241
+ method: "POST",
3242
+ body: {
3243
+ workingMemory,
3244
+ resourceId
3245
+ }
3246
+ });
3247
+ }
3248
+ /**
3249
+ * Retrieves all available scorers
3250
+ * @returns Promise containing list of available scorers
3251
+ */
3252
+ getScorers() {
3253
+ return this.request("/api/scores/scorers");
3254
+ }
3255
+ /**
3256
+ * Retrieves a scorer by ID
3257
+ * @param scorerId - ID of the scorer to retrieve
3258
+ * @returns Promise containing the scorer
3259
+ */
3260
+ getScorer(scorerId) {
3261
+ return this.request(`/api/scores/scorers/${encodeURIComponent(scorerId)}`);
3262
+ }
3263
+ getScoresByScorerId(params) {
3264
+ const { page, perPage, scorerId, entityId, entityType } = params;
3265
+ const searchParams = new URLSearchParams();
3266
+ if (entityId) {
3267
+ searchParams.set("entityId", entityId);
3268
+ }
3269
+ if (entityType) {
3270
+ searchParams.set("entityType", entityType);
3271
+ }
3272
+ if (page !== void 0) {
3273
+ searchParams.set("page", String(page));
3274
+ }
3275
+ if (perPage !== void 0) {
3276
+ searchParams.set("perPage", String(perPage));
3277
+ }
3278
+ const queryString = searchParams.toString();
3279
+ return this.request(`/api/scores/scorer/${encodeURIComponent(scorerId)}${queryString ? `?${queryString}` : ""}`);
3280
+ }
3281
+ /**
3282
+ * Retrieves scores by run ID
3283
+ * @param params - Parameters containing run ID and pagination options
3284
+ * @returns Promise containing scores and pagination info
3285
+ */
3286
+ getScoresByRunId(params) {
3287
+ const { runId, page, perPage } = params;
3288
+ const searchParams = new URLSearchParams();
3289
+ if (page !== void 0) {
3290
+ searchParams.set("page", String(page));
3291
+ }
3292
+ if (perPage !== void 0) {
3293
+ searchParams.set("perPage", String(perPage));
3294
+ }
3295
+ const queryString = searchParams.toString();
3296
+ return this.request(`/api/scores/run/${encodeURIComponent(runId)}${queryString ? `?${queryString}` : ""}`);
3297
+ }
3298
+ /**
3299
+ * Retrieves scores by entity ID and type
3300
+ * @param params - Parameters containing entity ID, type, and pagination options
3301
+ * @returns Promise containing scores and pagination info
3302
+ */
3303
+ getScoresByEntityId(params) {
3304
+ const { entityId, entityType, page, perPage } = params;
3305
+ const searchParams = new URLSearchParams();
3306
+ if (page !== void 0) {
3307
+ searchParams.set("page", String(page));
3308
+ }
3309
+ if (perPage !== void 0) {
3310
+ searchParams.set("perPage", String(perPage));
3311
+ }
3312
+ const queryString = searchParams.toString();
3313
+ return this.request(
3314
+ `/api/scores/entity/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}${queryString ? `?${queryString}` : ""}`
3315
+ );
3316
+ }
3317
+ /**
3318
+ * Saves a score
3319
+ * @param params - Parameters containing the score data to save
3320
+ * @returns Promise containing the saved score
3321
+ */
3322
+ saveScore(params) {
3323
+ return this.request("/api/scores", {
3324
+ method: "POST",
3325
+ body: params
3326
+ });
3327
+ }
3328
+ /**
3329
+ * Retrieves model providers with available keys
3330
+ * @returns Promise containing model providers with available keys
3331
+ */
3332
+ getModelProviders() {
3333
+ return this.request(`/api/model-providers`);
3334
+ }
3335
+ getAITrace(traceId) {
3336
+ return this.observability.getTrace(traceId);
3337
+ }
3338
+ getAITraces(params) {
3339
+ return this.observability.getTraces(params);
3340
+ }
3341
+ getScoresBySpan(params) {
3342
+ return this.observability.getScoresBySpan(params);
3343
+ }
3344
+ score(params) {
3345
+ return this.observability.score(params);
3346
+ }
2203
3347
  };
2204
3348
 
3349
+ // src/tools.ts
3350
+ var ClientTool = class {
3351
+ id;
3352
+ description;
3353
+ inputSchema;
3354
+ outputSchema;
3355
+ execute;
3356
+ constructor(opts) {
3357
+ this.id = opts.id;
3358
+ this.description = opts.description;
3359
+ this.inputSchema = opts.inputSchema;
3360
+ this.outputSchema = opts.outputSchema;
3361
+ this.execute = opts.execute;
3362
+ }
3363
+ };
3364
+ function createTool(opts) {
3365
+ return new ClientTool(opts);
3366
+ }
3367
+
3368
+ exports.ClientTool = ClientTool;
2205
3369
  exports.MastraClient = MastraClient;
3370
+ exports.createTool = createTool;
3371
+ //# sourceMappingURL=index.cjs.map
3372
+ //# sourceMappingURL=index.cjs.map