@mastra/client-js 0.0.0-course-20250527170450 → 0.0.0-createToolOptions-20250926094418

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 (77) hide show
  1. package/CHANGELOG.md +1682 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +8 -9
  4. package/dist/client.d.ts +289 -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 +2541 -666
  9. package/dist/index.cjs.map +1 -0
  10. package/dist/index.d.ts +5 -899
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +2542 -669
  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 +29 -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 +254 -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 +470 -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 +37 -21
  53. package/.turbo/turbo-build.log +0 -19
  54. package/dist/index.d.cts +0 -899
  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 -334
  59. package/src/example.ts +0 -64
  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 -197
  64. package/src/resources/base.ts +0 -70
  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.ts +0 -86
  70. package/src/resources/tool.ts +0 -45
  71. package/src/resources/vector.ts +0 -83
  72. package/src/resources/workflow.ts +0 -349
  73. package/src/types.ts +0 -313
  74. package/src/utils/index.ts +0 -11
  75. package/src/utils/zod-to-json-schema.ts +0 -10
  76. package/tsconfig.json +0 -5
  77. package/vitest.config.js +0 -8
package/dist/index.cjs CHANGED
@@ -1,206 +1,135 @@
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 runtimeContext = require('@mastra/core/runtime-context');
9
9
 
10
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
11
 
12
12
  var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
13
13
 
14
- // src/adapters/agui.ts
15
- var AGUIAdapter = class extends client.AbstractAgent {
16
- agent;
17
- resourceId;
18
- constructor({ agent, agentId, resourceId, ...rest }) {
19
- super({
20
- agentId,
21
- ...rest
22
- });
23
- this.agent = agent;
24
- this.resourceId = resourceId;
25
- }
26
- run(input) {
27
- return new rxjs.Observable((subscriber) => {
28
- const convertedMessages = convertMessagesToMastraMessages(input.messages);
29
- subscriber.next({
30
- type: client.EventType.RUN_STARTED,
31
- threadId: input.threadId,
32
- runId: input.runId
33
- });
34
- this.agent.stream({
35
- threadId: input.threadId,
36
- resourceId: this.resourceId ?? "",
37
- runId: input.runId,
38
- messages: convertedMessages,
39
- clientTools: input.tools.reduce(
40
- (acc, tool) => {
41
- acc[tool.name] = {
42
- id: tool.name,
43
- description: tool.description,
44
- inputSchema: tool.parameters
45
- };
46
- return acc;
47
- },
48
- {}
49
- )
50
- }).then((response) => {
51
- let currentMessageId = void 0;
52
- let isInTextMessage = false;
53
- return response.processDataStream({
54
- onTextPart: (text) => {
55
- if (currentMessageId === void 0) {
56
- currentMessageId = generateUUID();
57
- const message2 = {
58
- type: client.EventType.TEXT_MESSAGE_START,
59
- messageId: currentMessageId,
60
- role: "assistant"
61
- };
62
- subscriber.next(message2);
63
- isInTextMessage = true;
64
- }
65
- const message = {
66
- type: client.EventType.TEXT_MESSAGE_CONTENT,
67
- messageId: currentMessageId,
68
- delta: text
69
- };
70
- subscriber.next(message);
71
- },
72
- onFinishMessagePart: () => {
73
- if (currentMessageId !== void 0) {
74
- const message = {
75
- type: client.EventType.TEXT_MESSAGE_END,
76
- messageId: currentMessageId
77
- };
78
- subscriber.next(message);
79
- isInTextMessage = false;
80
- }
81
- subscriber.next({
82
- type: client.EventType.RUN_FINISHED,
83
- threadId: input.threadId,
84
- runId: input.runId
85
- });
86
- subscriber.complete();
87
- },
88
- onToolCallPart(streamPart) {
89
- const parentMessageId = currentMessageId || generateUUID();
90
- if (isInTextMessage) {
91
- const message = {
92
- type: client.EventType.TEXT_MESSAGE_END,
93
- messageId: parentMessageId
94
- };
95
- subscriber.next(message);
96
- isInTextMessage = false;
97
- }
98
- subscriber.next({
99
- type: client.EventType.TOOL_CALL_START,
100
- toolCallId: streamPart.toolCallId,
101
- toolCallName: streamPart.toolName,
102
- parentMessageId
103
- });
104
- subscriber.next({
105
- type: client.EventType.TOOL_CALL_ARGS,
106
- toolCallId: streamPart.toolCallId,
107
- delta: JSON.stringify(streamPart.args),
108
- parentMessageId
109
- });
110
- subscriber.next({
111
- type: client.EventType.TOOL_CALL_END,
112
- toolCallId: streamPart.toolCallId,
113
- parentMessageId
114
- });
115
- }
116
- });
117
- }).catch((error) => {
118
- console.error("error", error);
119
- subscriber.error(error);
120
- });
121
- return () => {
122
- };
123
- });
124
- }
125
- };
126
- function generateUUID() {
127
- if (typeof crypto !== "undefined") {
128
- if (typeof crypto.randomUUID === "function") {
129
- return crypto.randomUUID();
130
- }
131
- if (typeof crypto.getRandomValues === "function") {
132
- const buffer = new Uint8Array(16);
133
- crypto.getRandomValues(buffer);
134
- buffer[6] = buffer[6] & 15 | 64;
135
- buffer[8] = buffer[8] & 63 | 128;
136
- let hex = "";
137
- for (let i = 0; i < 16; i++) {
138
- hex += buffer[i].toString(16).padStart(2, "0");
139
- if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
140
- }
141
- 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());
142
19
  }
20
+ return runtimeContext$1;
143
21
  }
144
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
145
- const r = Math.random() * 16 | 0;
146
- const v = c === "x" ? r : r & 3 | 8;
147
- return v.toString(16);
148
- });
22
+ return void 0;
149
23
  }
150
- function convertMessagesToMastraMessages(messages) {
151
- const result = [];
152
- for (const message of messages) {
153
- if (message.role === "assistant") {
154
- const parts = message.content ? [{ type: "text", text: message.content }] : [];
155
- for (const toolCall of message.toolCalls ?? []) {
156
- parts.push({
157
- type: "tool-call",
158
- toolCallId: toolCall.id,
159
- toolName: toolCall.function.name,
160
- args: JSON.parse(toolCall.function.arguments)
161
- });
162
- }
163
- result.push({
164
- role: "assistant",
165
- content: parts
166
- });
167
- if (message.toolCalls?.length) {
168
- result.push({
169
- role: "tool",
170
- content: message.toolCalls.map((toolCall) => ({
171
- type: "tool-result",
172
- toolCallId: toolCall.id,
173
- toolName: toolCall.function.name,
174
- result: JSON.parse(toolCall.function.arguments)
175
- }))
176
- });
177
- }
178
- } else if (message.role === "user") {
179
- result.push({
180
- role: "user",
181
- content: message.content || ""
182
- });
183
- } else if (message.role === "tool") {
184
- result.push({
185
- role: "tool",
186
- content: [
187
- {
188
- type: "tool-result",
189
- toolCallId: message.toolCallId,
190
- toolName: "unknown",
191
- result: message.content
192
- }
193
- ]
194
- });
195
- }
24
+ function base64RuntimeContext(runtimeContext) {
25
+ if (runtimeContext) {
26
+ return btoa(JSON.stringify(runtimeContext));
196
27
  }
197
- 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";
198
40
  }
199
41
  function zodToJsonSchema(zodSchema) {
200
- if (!(zodSchema instanceof zod.ZodSchema)) {
42
+ if (!isZodType(zodSchema)) {
201
43
  return zodSchema;
202
44
  }
203
- 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" });
50
+ }
51
+
52
+ // src/utils/process-client-tools.ts
53
+ function processClientTools(clientTools) {
54
+ if (!clientTools) {
55
+ return void 0;
56
+ }
57
+ return Object.fromEntries(
58
+ Object.entries(clientTools).map(([key, value]) => {
59
+ if (isVercelTool.isVercelTool(value)) {
60
+ return [
61
+ key,
62
+ {
63
+ ...value,
64
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
65
+ }
66
+ ];
67
+ } else {
68
+ return [
69
+ key,
70
+ {
71
+ ...value,
72
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
73
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
74
+ }
75
+ ];
76
+ }
77
+ })
78
+ );
79
+ }
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
+ });
204
133
  }
205
134
 
206
135
  // src/resources/base.ts
@@ -217,18 +146,21 @@ var BaseResource = class {
217
146
  */
218
147
  async request(path, options = {}) {
219
148
  let lastError = null;
220
- const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
149
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {}, credentials } = this.options;
221
150
  let delay = backoffMs;
222
151
  for (let attempt = 0; attempt <= retries; attempt++) {
223
152
  try {
224
153
  const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
225
154
  ...options,
226
155
  headers: {
156
+ ...options.body && !(options.body instanceof FormData) && (options.method === "POST" || options.method === "PUT") ? { "content-type": "application/json" } : {},
227
157
  ...headers,
228
158
  ...options.headers
229
159
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
230
160
  // 'x-mastra-client-type': 'js',
231
161
  },
162
+ signal: this.options.abortSignal,
163
+ credentials: options.credentials ?? credentials,
232
164
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
233
165
  });
234
166
  if (!response.ok) {
@@ -261,17 +193,63 @@ var BaseResource = class {
261
193
  throw lastError || new Error("Request failed");
262
194
  }
263
195
  };
264
- function parseClientRuntimeContext(runtimeContext$1) {
265
- if (runtimeContext$1) {
266
- if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
267
- 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
+ }
268
250
  }
269
- return runtimeContext$1;
270
251
  }
271
- return void 0;
272
252
  }
273
-
274
- // src/resources/agent.ts
275
253
  var AgentVoice = class extends BaseResource {
276
254
  constructor(options, agentId) {
277
255
  super(options);
@@ -313,10 +291,21 @@ var AgentVoice = class extends BaseResource {
313
291
  }
314
292
  /**
315
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
316
296
  * @returns Promise containing list of available speakers
317
297
  */
318
- getSpeakers() {
319
- return this.request(`/api/agents/${this.agentId}/voice/speakers`);
298
+ getSpeakers(runtimeContext) {
299
+ return this.request(`/api/agents/${this.agentId}/voice/speakers${runtimeContextQueryString(runtimeContext)}`);
300
+ }
301
+ /**
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
305
+ * @returns Promise containing a check if the agent has listening capabilities
306
+ */
307
+ getListener(runtimeContext) {
308
+ return this.request(`/api/agents/${this.agentId}/voice/listener${runtimeContextQueryString(runtimeContext)}`);
320
309
  }
321
310
  };
322
311
  var Agent = class extends BaseResource {
@@ -328,154 +317,1048 @@ var Agent = class extends BaseResource {
328
317
  voice;
329
318
  /**
330
319
  * Retrieves details about the agent
320
+ * @param runtimeContext - Optional runtime context to pass as query parameter
331
321
  * @returns Promise containing agent details including model and instructions
332
322
  */
333
- details() {
334
- return this.request(`/api/agents/${this.agentId}`);
323
+ details(runtimeContext) {
324
+ return this.request(`/api/agents/${this.agentId}${runtimeContextQueryString(runtimeContext)}`);
335
325
  }
336
- /**
337
- * Generates a response from the agent
338
- * @param params - Generation parameters including prompt
339
- * @returns Promise containing the generated response
340
- */
341
- generate(params) {
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) {
342
333
  const processedParams = {
343
334
  ...params,
344
335
  output: params.output ? zodToJsonSchema(params.output) : void 0,
345
336
  experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
346
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
337
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
338
+ clientTools: processClientTools(params.clientTools)
347
339
  };
348
- return this.request(`/api/agents/${this.agentId}/generate`, {
349
- method: "POST",
350
- body: processedParams
351
- });
340
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
341
+ const response = await this.request(
342
+ `/api/agents/${this.agentId}/generate-legacy`,
343
+ {
344
+ method: "POST",
345
+ body: processedParams
346
+ }
347
+ );
348
+ if (response.finishReason === "tool-calls") {
349
+ const toolCalls = response.toolCalls;
350
+ if (!toolCalls || !Array.isArray(toolCalls)) {
351
+ return response;
352
+ }
353
+ for (const toolCall of toolCalls) {
354
+ const clientTool = params.clientTools?.[toolCall.toolName];
355
+ if (clientTool && clientTool.execute) {
356
+ const result = await clientTool.execute(
357
+ {
358
+ context: toolCall?.args,
359
+ runId,
360
+ resourceId,
361
+ threadId,
362
+ runtimeContext,
363
+ tracingContext: { currentSpan: void 0 },
364
+ suspend: async () => {
365
+ }
366
+ },
367
+ {
368
+ messages: response.messages,
369
+ toolCallId: toolCall?.toolCallId
370
+ }
371
+ );
372
+ const updatedMessages = [
373
+ ...response.response.messages,
374
+ {
375
+ role: "tool",
376
+ content: [
377
+ {
378
+ type: "tool-result",
379
+ toolCallId: toolCall.toolCallId,
380
+ toolName: toolCall.toolName,
381
+ result
382
+ }
383
+ ]
384
+ }
385
+ ];
386
+ return this.generate({
387
+ ...params,
388
+ messages: updatedMessages
389
+ });
390
+ }
391
+ }
392
+ }
393
+ return response;
352
394
  }
353
- /**
354
- * Streams a response from the agent
355
- * @param params - Stream parameters including prompt
356
- * @returns Promise containing the enhanced Response object with processDataStream method
357
- */
358
- async stream(params) {
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
+ }
359
405
  const processedParams = {
360
406
  ...params,
361
407
  output: params.output ? zodToJsonSchema(params.output) : void 0,
362
- experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
363
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
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
364
414
  };
365
- const response = await this.request(`/api/agents/${this.agentId}/stream`, {
366
- method: "POST",
367
- body: processedParams,
368
- stream: true
369
- });
370
- if (!response.body) {
371
- throw new Error("No response body");
372
- }
373
- response.processDataStream = async (options = {}) => {
374
- await uiUtils.processDataStream({
375
- stream: response.body,
376
- ...options
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)
377
432
  });
378
- };
433
+ }
379
434
  return response;
380
435
  }
381
- /**
382
- * Gets details about a specific tool available to the agent
383
- * @param toolId - ID of the tool to retrieve
384
- * @returns Promise containing tool details
385
- */
386
- getTool(toolId) {
387
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
388
- }
389
- /**
390
- * Executes a tool for the agent
391
- * @param toolId - ID of the tool to execute
392
- * @param params - Parameters required for tool execution
393
- * @returns Promise containing the tool execution results
394
- */
395
- executeTool(toolId, params) {
396
- const body = {
397
- data: params.data,
398
- runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
436
+ async processChatResponse({
437
+ stream,
438
+ update,
439
+ onToolCall,
440
+ onFinish,
441
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
442
+ lastMessage
443
+ }) {
444
+ const replaceLastMessage = lastMessage?.role === "assistant";
445
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
446
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
447
+ return Math.max(max, toolInvocation.step ?? 0);
448
+ }, 0) ?? 0) : 0;
449
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
450
+ id: uuid.v4(),
451
+ createdAt: getCurrentDate(),
452
+ role: "assistant",
453
+ content: "",
454
+ parts: []
399
455
  };
400
- return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
401
- method: "POST",
402
- body
456
+ let currentTextPart = void 0;
457
+ let currentReasoningPart = void 0;
458
+ let currentReasoningTextDetail = void 0;
459
+ function updateToolInvocationPart(toolCallId, invocation) {
460
+ const part = message.parts.find(
461
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
462
+ );
463
+ if (part != null) {
464
+ part.toolInvocation = invocation;
465
+ } else {
466
+ message.parts.push({
467
+ type: "tool-invocation",
468
+ toolInvocation: invocation
469
+ });
470
+ }
471
+ }
472
+ const data = [];
473
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
474
+ const partialToolCalls = {};
475
+ let usage = {
476
+ completionTokens: NaN,
477
+ promptTokens: NaN,
478
+ totalTokens: NaN
479
+ };
480
+ let finishReason = "unknown";
481
+ function execUpdate() {
482
+ const copiedData = [...data];
483
+ if (messageAnnotations?.length) {
484
+ message.annotations = messageAnnotations;
485
+ }
486
+ const copiedMessage = {
487
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
488
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
489
+ ...structuredClone(message),
490
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
491
+ // hashing approach by default to detect changes, but it only works for shallow
492
+ // changes. This is why we need to add a revision id to ensure that the message
493
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
494
+ // forwarded to rendering):
495
+ revisionId: uuid.v4()
496
+ };
497
+ update({
498
+ message: copiedMessage,
499
+ data: copiedData,
500
+ replaceLastMessage
501
+ });
502
+ }
503
+ await uiUtils.processDataStream({
504
+ stream,
505
+ onTextPart(value) {
506
+ if (currentTextPart == null) {
507
+ currentTextPart = {
508
+ type: "text",
509
+ text: value
510
+ };
511
+ message.parts.push(currentTextPart);
512
+ } else {
513
+ currentTextPart.text += value;
514
+ }
515
+ message.content += value;
516
+ execUpdate();
517
+ },
518
+ onReasoningPart(value) {
519
+ if (currentReasoningTextDetail == null) {
520
+ currentReasoningTextDetail = { type: "text", text: value };
521
+ if (currentReasoningPart != null) {
522
+ currentReasoningPart.details.push(currentReasoningTextDetail);
523
+ }
524
+ } else {
525
+ currentReasoningTextDetail.text += value;
526
+ }
527
+ if (currentReasoningPart == null) {
528
+ currentReasoningPart = {
529
+ type: "reasoning",
530
+ reasoning: value,
531
+ details: [currentReasoningTextDetail]
532
+ };
533
+ message.parts.push(currentReasoningPart);
534
+ } else {
535
+ currentReasoningPart.reasoning += value;
536
+ }
537
+ message.reasoning = (message.reasoning ?? "") + value;
538
+ execUpdate();
539
+ },
540
+ onReasoningSignaturePart(value) {
541
+ if (currentReasoningTextDetail != null) {
542
+ currentReasoningTextDetail.signature = value.signature;
543
+ }
544
+ },
545
+ onRedactedReasoningPart(value) {
546
+ if (currentReasoningPart == null) {
547
+ currentReasoningPart = {
548
+ type: "reasoning",
549
+ reasoning: "",
550
+ details: []
551
+ };
552
+ message.parts.push(currentReasoningPart);
553
+ }
554
+ currentReasoningPart.details.push({
555
+ type: "redacted",
556
+ data: value.data
557
+ });
558
+ currentReasoningTextDetail = void 0;
559
+ execUpdate();
560
+ },
561
+ onFilePart(value) {
562
+ message.parts.push({
563
+ type: "file",
564
+ mimeType: value.mimeType,
565
+ data: value.data
566
+ });
567
+ execUpdate();
568
+ },
569
+ onSourcePart(value) {
570
+ message.parts.push({
571
+ type: "source",
572
+ source: value
573
+ });
574
+ execUpdate();
575
+ },
576
+ onToolCallStreamingStartPart(value) {
577
+ if (message.toolInvocations == null) {
578
+ message.toolInvocations = [];
579
+ }
580
+ partialToolCalls[value.toolCallId] = {
581
+ text: "",
582
+ step,
583
+ toolName: value.toolName,
584
+ index: message.toolInvocations.length
585
+ };
586
+ const invocation = {
587
+ state: "partial-call",
588
+ step,
589
+ toolCallId: value.toolCallId,
590
+ toolName: value.toolName,
591
+ args: void 0
592
+ };
593
+ message.toolInvocations.push(invocation);
594
+ updateToolInvocationPart(value.toolCallId, invocation);
595
+ execUpdate();
596
+ },
597
+ onToolCallDeltaPart(value) {
598
+ const partialToolCall = partialToolCalls[value.toolCallId];
599
+ partialToolCall.text += value.argsTextDelta;
600
+ const { value: partialArgs } = uiUtils.parsePartialJson(partialToolCall.text);
601
+ const invocation = {
602
+ state: "partial-call",
603
+ step: partialToolCall.step,
604
+ toolCallId: value.toolCallId,
605
+ toolName: partialToolCall.toolName,
606
+ args: partialArgs
607
+ };
608
+ message.toolInvocations[partialToolCall.index] = invocation;
609
+ updateToolInvocationPart(value.toolCallId, invocation);
610
+ execUpdate();
611
+ },
612
+ async onToolCallPart(value) {
613
+ const invocation = {
614
+ state: "call",
615
+ step,
616
+ ...value
617
+ };
618
+ if (partialToolCalls[value.toolCallId] != null) {
619
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
620
+ } else {
621
+ if (message.toolInvocations == null) {
622
+ message.toolInvocations = [];
623
+ }
624
+ message.toolInvocations.push(invocation);
625
+ }
626
+ updateToolInvocationPart(value.toolCallId, invocation);
627
+ execUpdate();
628
+ if (onToolCall) {
629
+ const result = await onToolCall({ toolCall: value });
630
+ if (result != null) {
631
+ const invocation2 = {
632
+ state: "result",
633
+ step,
634
+ ...value,
635
+ result
636
+ };
637
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
638
+ updateToolInvocationPart(value.toolCallId, invocation2);
639
+ execUpdate();
640
+ }
641
+ }
642
+ },
643
+ onToolResultPart(value) {
644
+ const toolInvocations = message.toolInvocations;
645
+ if (toolInvocations == null) {
646
+ throw new Error("tool_result must be preceded by a tool_call");
647
+ }
648
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
649
+ if (toolInvocationIndex === -1) {
650
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
651
+ }
652
+ const invocation = {
653
+ ...toolInvocations[toolInvocationIndex],
654
+ state: "result",
655
+ ...value
656
+ };
657
+ toolInvocations[toolInvocationIndex] = invocation;
658
+ updateToolInvocationPart(value.toolCallId, invocation);
659
+ execUpdate();
660
+ },
661
+ onDataPart(value) {
662
+ data.push(...value);
663
+ execUpdate();
664
+ },
665
+ onMessageAnnotationsPart(value) {
666
+ if (messageAnnotations == null) {
667
+ messageAnnotations = [...value];
668
+ } else {
669
+ messageAnnotations.push(...value);
670
+ }
671
+ execUpdate();
672
+ },
673
+ onFinishStepPart(value) {
674
+ step += 1;
675
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
676
+ currentReasoningPart = void 0;
677
+ currentReasoningTextDetail = void 0;
678
+ },
679
+ onStartStepPart(value) {
680
+ if (!replaceLastMessage) {
681
+ message.id = value.messageId;
682
+ }
683
+ message.parts.push({ type: "step-start" });
684
+ execUpdate();
685
+ },
686
+ onFinishMessagePart(value) {
687
+ finishReason = value.finishReason;
688
+ if (value.usage != null) {
689
+ usage = value.usage;
690
+ }
691
+ },
692
+ onErrorPart(error) {
693
+ throw new Error(error);
694
+ }
403
695
  });
696
+ onFinish?.({ message, finishReason, usage });
404
697
  }
405
698
  /**
406
- * Retrieves evaluation results for the agent
407
- * @returns Promise containing agent evaluations
408
- */
409
- evals() {
410
- return this.request(`/api/agents/${this.agentId}/evals/ci`);
411
- }
412
- /**
413
- * Retrieves live evaluation results for the agent
414
- * @returns Promise containing live agent evaluations
415
- */
416
- liveEvals() {
417
- return this.request(`/api/agents/${this.agentId}/evals/live`);
418
- }
419
- };
420
- var Network = class extends BaseResource {
421
- constructor(options, networkId) {
422
- super(options);
423
- this.networkId = networkId;
424
- }
425
- /**
426
- * Retrieves details about the network
427
- * @returns Promise containing network details
428
- */
429
- details() {
430
- return this.request(`/api/networks/${this.networkId}`);
431
- }
432
- /**
433
- * Generates a response from the agent
434
- * @param params - Generation parameters including prompt
435
- * @returns Promise containing the generated response
699
+ * Streams a response from the agent
700
+ * @param params - Stream parameters including prompt
701
+ * @returns Promise containing the enhanced Response object with processDataStream method
436
702
  */
437
- generate(params) {
438
- const processedParams = {
439
- ...params,
440
- output: zodToJsonSchema(params.output),
441
- experimental_output: zodToJsonSchema(params.experimental_output)
442
- };
443
- return this.request(`/api/networks/${this.networkId}/generate`, {
444
- method: "POST",
445
- body: processedParams
446
- });
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);
447
708
  }
448
709
  /**
449
710
  * Streams a response from the agent
450
711
  * @param params - Stream parameters including prompt
451
712
  * @returns Promise containing the enhanced Response object with processDataStream method
452
713
  */
453
- async stream(params) {
714
+ async streamLegacy(params) {
454
715
  const processedParams = {
455
716
  ...params,
456
- output: zodToJsonSchema(params.output),
457
- experimental_output: zodToJsonSchema(params.experimental_output)
717
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
718
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
719
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
720
+ clientTools: processClientTools(params.clientTools)
458
721
  };
459
- const response = await this.request(`/api/networks/${this.networkId}/stream`, {
460
- method: "POST",
461
- body: processedParams,
462
- stream: true
722
+ const { readable, writable } = new TransformStream();
723
+ const response = await this.processStreamResponse(processedParams, writable);
724
+ const streamResponse = new Response(readable, {
725
+ status: response.status,
726
+ statusText: response.statusText,
727
+ headers: response.headers
463
728
  });
464
- if (!response.body) {
465
- throw new Error("No response body");
466
- }
467
- response.processDataStream = async (options = {}) => {
729
+ streamResponse.processDataStream = async (options = {}) => {
468
730
  await uiUtils.processDataStream({
469
- stream: response.body,
731
+ stream: streamResponse.body,
470
732
  ...options
471
733
  });
472
734
  };
473
- return response;
474
- }
475
- };
476
-
477
- // src/resources/memory-thread.ts
478
- var MemoryThread = class extends BaseResource {
735
+ return streamResponse;
736
+ }
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`, {
992
+ method: "POST",
993
+ body: processedParams,
994
+ stream: true
995
+ });
996
+ if (!response.body) {
997
+ throw new Error("No response body");
998
+ }
999
+ try {
1000
+ let toolCalls = [];
1001
+ let messages = [];
1002
+ const [streamForWritable, streamForProcessing] = response.body.tee();
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
+ for (const toolCall2 of toolCalls) {
1044
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1045
+ if (clientTool && clientTool.execute) {
1046
+ const result = await clientTool.execute(
1047
+ {
1048
+ context: toolCall2?.args,
1049
+ runId: processedParams.runId,
1050
+ resourceId: processedParams.resourceId,
1051
+ threadId: processedParams.threadId,
1052
+ runtimeContext: processedParams.runtimeContext,
1053
+ // TODO: Pass proper tracing context when client-js supports tracing
1054
+ tracingContext: { currentSpan: void 0 },
1055
+ suspend: async () => {
1056
+ }
1057
+ },
1058
+ {
1059
+ messages: response.messages,
1060
+ toolCallId: toolCall2?.toolCallId
1061
+ }
1062
+ );
1063
+ const lastMessageRaw = messages[messages.length - 1];
1064
+ const lastMessage = lastMessageRaw != null ? JSON.parse(JSON.stringify(lastMessageRaw)) : void 0;
1065
+ const toolInvocationPart = lastMessage?.parts?.find(
1066
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1067
+ );
1068
+ if (toolInvocationPart) {
1069
+ toolInvocationPart.toolInvocation = {
1070
+ ...toolInvocationPart.toolInvocation,
1071
+ state: "result",
1072
+ result
1073
+ };
1074
+ }
1075
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1076
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1077
+ );
1078
+ if (toolInvocation) {
1079
+ toolInvocation.state = "result";
1080
+ toolInvocation.result = result;
1081
+ }
1082
+ const updatedMessages = lastMessage != null ? [...messages.filter((m) => m.id !== lastMessage.id), lastMessage] : [...messages];
1083
+ this.processStreamResponse_vNext(
1084
+ {
1085
+ ...processedParams,
1086
+ messages: updatedMessages
1087
+ },
1088
+ writable
1089
+ ).catch((error) => {
1090
+ console.error("Error processing stream response:", error);
1091
+ });
1092
+ }
1093
+ }
1094
+ } else {
1095
+ setTimeout(() => {
1096
+ writable.close();
1097
+ }, 0);
1098
+ }
1099
+ },
1100
+ lastMessage: void 0
1101
+ }).catch((error) => {
1102
+ console.error("Error processing stream response:", error);
1103
+ });
1104
+ } catch (error) {
1105
+ console.error("Error processing stream response:", error);
1106
+ }
1107
+ return response;
1108
+ }
1109
+ async network(params) {
1110
+ const response = await this.request(`/api/agents/${this.agentId}/network`, {
1111
+ method: "POST",
1112
+ body: params,
1113
+ stream: true
1114
+ });
1115
+ if (!response.body) {
1116
+ throw new Error("No response body");
1117
+ }
1118
+ const streamResponse = new Response(response.body, {
1119
+ status: response.status,
1120
+ statusText: response.statusText,
1121
+ headers: response.headers
1122
+ });
1123
+ streamResponse.processDataStream = async ({
1124
+ onChunk
1125
+ }) => {
1126
+ await processMastraNetworkStream({
1127
+ stream: streamResponse.body,
1128
+ onChunk
1129
+ });
1130
+ };
1131
+ return streamResponse;
1132
+ }
1133
+ async streamVNext(messagesOrParams, options) {
1134
+ let params;
1135
+ if (typeof messagesOrParams === "object" && "messages" in messagesOrParams) {
1136
+ params = messagesOrParams;
1137
+ } else {
1138
+ params = {
1139
+ messages: messagesOrParams,
1140
+ ...options
1141
+ };
1142
+ }
1143
+ const processedParams = {
1144
+ ...params,
1145
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
1146
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
1147
+ clientTools: processClientTools(params.clientTools),
1148
+ structuredOutput: params.structuredOutput ? {
1149
+ ...params.structuredOutput,
1150
+ schema: zodToJsonSchema(params.structuredOutput.schema)
1151
+ } : void 0
1152
+ };
1153
+ const { readable, writable } = new TransformStream();
1154
+ const response = await this.processStreamResponse_vNext(processedParams, writable);
1155
+ const streamResponse = new Response(readable, {
1156
+ status: response.status,
1157
+ statusText: response.statusText,
1158
+ headers: response.headers
1159
+ });
1160
+ streamResponse.processDataStream = async ({
1161
+ onChunk
1162
+ }) => {
1163
+ await processMastraStream({
1164
+ stream: streamResponse.body,
1165
+ onChunk
1166
+ });
1167
+ };
1168
+ return streamResponse;
1169
+ }
1170
+ /**
1171
+ * Processes the stream response and handles tool calls
1172
+ */
1173
+ async processStreamResponse(processedParams, writable) {
1174
+ const response = await this.request(`/api/agents/${this.agentId}/stream-legacy`, {
1175
+ method: "POST",
1176
+ body: processedParams,
1177
+ stream: true
1178
+ });
1179
+ if (!response.body) {
1180
+ throw new Error("No response body");
1181
+ }
1182
+ try {
1183
+ let toolCalls = [];
1184
+ let messages = [];
1185
+ const [streamForWritable, streamForProcessing] = response.body.tee();
1186
+ streamForWritable.pipeTo(writable, {
1187
+ preventClose: true
1188
+ }).catch((error) => {
1189
+ console.error("Error piping to writable stream:", error);
1190
+ });
1191
+ this.processChatResponse({
1192
+ stream: streamForProcessing,
1193
+ update: ({ message }) => {
1194
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
1195
+ if (existingIndex !== -1) {
1196
+ messages[existingIndex] = message;
1197
+ } else {
1198
+ messages.push(message);
1199
+ }
1200
+ },
1201
+ onFinish: async ({ finishReason, message }) => {
1202
+ if (finishReason === "tool-calls") {
1203
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
1204
+ if (toolCall) {
1205
+ toolCalls.push(toolCall);
1206
+ }
1207
+ for (const toolCall2 of toolCalls) {
1208
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
1209
+ if (clientTool && clientTool.execute) {
1210
+ const result = await clientTool.execute(
1211
+ {
1212
+ context: toolCall2?.args,
1213
+ runId: processedParams.runId,
1214
+ resourceId: processedParams.resourceId,
1215
+ threadId: processedParams.threadId,
1216
+ runtimeContext: processedParams.runtimeContext,
1217
+ // TODO: Pass proper tracing context when client-js supports tracing
1218
+ tracingContext: { currentSpan: void 0 },
1219
+ suspend: async () => {
1220
+ }
1221
+ },
1222
+ {
1223
+ messages: response.messages,
1224
+ toolCallId: toolCall2?.toolCallId
1225
+ }
1226
+ );
1227
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
1228
+ const toolInvocationPart = lastMessage?.parts?.find(
1229
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
1230
+ );
1231
+ if (toolInvocationPart) {
1232
+ toolInvocationPart.toolInvocation = {
1233
+ ...toolInvocationPart.toolInvocation,
1234
+ state: "result",
1235
+ result
1236
+ };
1237
+ }
1238
+ const toolInvocation = lastMessage?.toolInvocations?.find(
1239
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
1240
+ );
1241
+ if (toolInvocation) {
1242
+ toolInvocation.state = "result";
1243
+ toolInvocation.result = result;
1244
+ }
1245
+ const writer = writable.getWriter();
1246
+ try {
1247
+ await writer.write(
1248
+ new TextEncoder().encode(
1249
+ "a:" + JSON.stringify({
1250
+ toolCallId: toolCall2.toolCallId,
1251
+ result
1252
+ }) + "\n"
1253
+ )
1254
+ );
1255
+ } finally {
1256
+ writer.releaseLock();
1257
+ }
1258
+ this.processStreamResponse(
1259
+ {
1260
+ ...processedParams,
1261
+ messages: [...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
1262
+ },
1263
+ writable
1264
+ ).catch((error) => {
1265
+ console.error("Error processing stream response:", error);
1266
+ });
1267
+ }
1268
+ }
1269
+ } else {
1270
+ setTimeout(() => {
1271
+ writable.close();
1272
+ }, 0);
1273
+ }
1274
+ },
1275
+ lastMessage: void 0
1276
+ }).catch((error) => {
1277
+ console.error("Error processing stream response:", error);
1278
+ });
1279
+ } catch (error) {
1280
+ console.error("Error processing stream response:", error);
1281
+ }
1282
+ return response;
1283
+ }
1284
+ /**
1285
+ * Gets details about a specific tool available to the agent
1286
+ * @param toolId - ID of the tool to retrieve
1287
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1288
+ * @returns Promise containing tool details
1289
+ */
1290
+ getTool(toolId, runtimeContext) {
1291
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}${runtimeContextQueryString(runtimeContext)}`);
1292
+ }
1293
+ /**
1294
+ * Executes a tool for the agent
1295
+ * @param toolId - ID of the tool to execute
1296
+ * @param params - Parameters required for tool execution
1297
+ * @returns Promise containing the tool execution results
1298
+ */
1299
+ executeTool(toolId, params) {
1300
+ const body = {
1301
+ data: params.data,
1302
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1303
+ };
1304
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
1305
+ method: "POST",
1306
+ body
1307
+ });
1308
+ }
1309
+ /**
1310
+ * Retrieves evaluation results for the agent
1311
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1312
+ * @returns Promise containing agent evaluations
1313
+ */
1314
+ evals(runtimeContext) {
1315
+ return this.request(`/api/agents/${this.agentId}/evals/ci${runtimeContextQueryString(runtimeContext)}`);
1316
+ }
1317
+ /**
1318
+ * Retrieves live evaluation results for the agent
1319
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1320
+ * @returns Promise containing live agent evaluations
1321
+ */
1322
+ liveEvals(runtimeContext) {
1323
+ return this.request(`/api/agents/${this.agentId}/evals/live${runtimeContextQueryString(runtimeContext)}`);
1324
+ }
1325
+ /**
1326
+ * Updates the model for the agent
1327
+ * @param params - Parameters for updating the model
1328
+ * @returns Promise containing the updated model
1329
+ */
1330
+ updateModel(params) {
1331
+ return this.request(`/api/agents/${this.agentId}/model`, {
1332
+ method: "POST",
1333
+ body: params
1334
+ });
1335
+ }
1336
+ /**
1337
+ * Updates the model for the agent in the model list
1338
+ * @param params - Parameters for updating the model
1339
+ * @returns Promise containing the updated model
1340
+ */
1341
+ updateModelInModelList({ modelConfigId, ...params }) {
1342
+ return this.request(`/api/agents/${this.agentId}/models/${modelConfigId}`, {
1343
+ method: "POST",
1344
+ body: params
1345
+ });
1346
+ }
1347
+ /**
1348
+ * Reorders the models for the agent
1349
+ * @param params - Parameters for reordering the model list
1350
+ * @returns Promise containing the updated model list
1351
+ */
1352
+ reorderModelList(params) {
1353
+ return this.request(`/api/agents/${this.agentId}/models/reorder`, {
1354
+ method: "POST",
1355
+ body: params
1356
+ });
1357
+ }
1358
+ };
1359
+
1360
+ // src/resources/memory-thread.ts
1361
+ var MemoryThread = class extends BaseResource {
479
1362
  constructor(options, threadId, agentId) {
480
1363
  super(options);
481
1364
  this.threadId = threadId;
@@ -520,6 +1403,36 @@ var MemoryThread = class extends BaseResource {
520
1403
  });
521
1404
  return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
522
1405
  }
1406
+ /**
1407
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
1408
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
1409
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
1410
+ */
1411
+ getMessagesPaginated({
1412
+ selectBy,
1413
+ ...rest
1414
+ }) {
1415
+ const query = new URLSearchParams({
1416
+ ...rest,
1417
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
1418
+ });
1419
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
1420
+ }
1421
+ /**
1422
+ * Deletes one or more messages from the thread
1423
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1424
+ * message object with id property, or array of message objects
1425
+ * @returns Promise containing deletion result
1426
+ */
1427
+ deleteMessages(messageIds) {
1428
+ const query = new URLSearchParams({
1429
+ agentId: this.agentId
1430
+ });
1431
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
1432
+ method: "POST",
1433
+ body: { messageIds }
1434
+ });
1435
+ }
523
1436
  };
524
1437
 
525
1438
  // src/resources/vector.ts
@@ -531,10 +1444,13 @@ var Vector = class extends BaseResource {
531
1444
  /**
532
1445
  * Retrieves details about a specific vector index
533
1446
  * @param indexName - Name of the index to get details for
1447
+ * @param runtimeContext - Optional runtime context to pass as query parameter
534
1448
  * @returns Promise containing vector index details
535
1449
  */
536
- details(indexName) {
537
- return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
1450
+ details(indexName, runtimeContext) {
1451
+ return this.request(
1452
+ `/api/vector/${this.vectorName}/indexes/${indexName}${runtimeContextQueryString(runtimeContext)}`
1453
+ );
538
1454
  }
539
1455
  /**
540
1456
  * Deletes a vector index
@@ -548,10 +1464,11 @@ var Vector = class extends BaseResource {
548
1464
  }
549
1465
  /**
550
1466
  * Retrieves a list of all available indexes
1467
+ * @param runtimeContext - Optional runtime context to pass as query parameter
551
1468
  * @returns Promise containing array of index names
552
1469
  */
553
- getIndexes() {
554
- return this.request(`/api/vector/${this.vectorName}/indexes`);
1470
+ getIndexes(runtimeContext) {
1471
+ return this.request(`/api/vector/${this.vectorName}/indexes${runtimeContextQueryString(runtimeContext)}`);
555
1472
  }
556
1473
  /**
557
1474
  * Creates a new vector index
@@ -588,227 +1505,47 @@ var Vector = class extends BaseResource {
588
1505
  }
589
1506
  };
590
1507
 
591
- // src/resources/legacy-workflow.ts
592
- var RECORD_SEPARATOR = "";
593
- var LegacyWorkflow = class extends BaseResource {
594
- constructor(options, workflowId) {
1508
+ // src/resources/tool.ts
1509
+ var Tool = class extends BaseResource {
1510
+ constructor(options, toolId) {
595
1511
  super(options);
596
- this.workflowId = workflowId;
597
- }
598
- /**
599
- * Retrieves details about the legacy workflow
600
- * @returns Promise containing legacy workflow details including steps and graphs
601
- */
602
- details() {
603
- return this.request(`/api/workflows/legacy/${this.workflowId}`);
1512
+ this.toolId = toolId;
604
1513
  }
605
1514
  /**
606
- * Retrieves all runs for a legacy workflow
607
- * @param params - Parameters for filtering runs
608
- * @returns Promise containing legacy workflow runs array
1515
+ * Retrieves details about the tool
1516
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1517
+ * @returns Promise containing tool details including description and schemas
609
1518
  */
610
- runs(params) {
611
- const searchParams = new URLSearchParams();
612
- if (params?.fromDate) {
613
- searchParams.set("fromDate", params.fromDate.toISOString());
614
- }
615
- if (params?.toDate) {
616
- searchParams.set("toDate", params.toDate.toISOString());
617
- }
618
- if (params?.limit) {
619
- searchParams.set("limit", String(params.limit));
620
- }
621
- if (params?.offset) {
622
- searchParams.set("offset", String(params.offset));
623
- }
624
- if (params?.resourceId) {
625
- searchParams.set("resourceId", params.resourceId);
626
- }
627
- if (searchParams.size) {
628
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
629
- } else {
630
- return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
631
- }
1519
+ details(runtimeContext) {
1520
+ return this.request(`/api/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
632
1521
  }
633
1522
  /**
634
- * Creates a new legacy workflow run
635
- * @returns Promise containing the generated run ID
1523
+ * Executes the tool with the provided parameters
1524
+ * @param params - Parameters required for tool execution
1525
+ * @returns Promise containing the tool execution results
636
1526
  */
637
- createRun(params) {
638
- const searchParams = new URLSearchParams();
639
- if (!!params?.runId) {
640
- searchParams.set("runId", params.runId);
1527
+ execute(params) {
1528
+ const url = new URLSearchParams();
1529
+ if (params.runId) {
1530
+ url.set("runId", params.runId);
641
1531
  }
642
- return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
643
- method: "POST"
644
- });
645
- }
646
- /**
647
- * Starts a legacy workflow run synchronously without waiting for the workflow to complete
648
- * @param params - Object containing the runId and triggerData
649
- * @returns Promise containing success message
650
- */
651
- start(params) {
652
- return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
1532
+ const body = {
1533
+ data: params.data,
1534
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1535
+ };
1536
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
653
1537
  method: "POST",
654
- body: params?.triggerData
1538
+ body
655
1539
  });
656
- }
657
- /**
658
- * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
659
- * @param stepId - ID of the step to resume
660
- * @param runId - ID of the legacy workflow run
661
- * @param context - Context to resume the legacy workflow with
662
- * @returns Promise containing the legacy workflow resume results
663
- */
664
- resume({
665
- stepId,
666
- runId,
667
- context
668
- }) {
669
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
670
- method: "POST",
671
- body: {
672
- stepId,
673
- context
674
- }
675
- });
676
- }
677
- /**
678
- * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
679
- * @param params - Object containing the optional runId and triggerData
680
- * @returns Promise containing the workflow execution results
681
- */
682
- startAsync(params) {
683
- const searchParams = new URLSearchParams();
684
- if (!!params?.runId) {
685
- searchParams.set("runId", params.runId);
686
- }
687
- return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
688
- method: "POST",
689
- body: params?.triggerData
690
- });
691
- }
692
- /**
693
- * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
694
- * @param params - Object containing the runId, stepId, and context
695
- * @returns Promise containing the workflow resume results
696
- */
697
- resumeAsync(params) {
698
- return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
699
- method: "POST",
700
- body: {
701
- stepId: params.stepId,
702
- context: params.context
703
- }
704
- });
705
- }
706
- /**
707
- * Creates an async generator that processes a readable stream and yields records
708
- * separated by the Record Separator character (\x1E)
709
- *
710
- * @param stream - The readable stream to process
711
- * @returns An async generator that yields parsed records
712
- */
713
- async *streamProcessor(stream) {
714
- const reader = stream.getReader();
715
- let doneReading = false;
716
- let buffer = "";
717
- try {
718
- while (!doneReading) {
719
- const { done, value } = await reader.read();
720
- doneReading = done;
721
- if (done && !value) continue;
722
- try {
723
- const decoded = value ? new TextDecoder().decode(value) : "";
724
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
725
- buffer = chunks.pop() || "";
726
- for (const chunk of chunks) {
727
- if (chunk) {
728
- if (typeof chunk === "string") {
729
- try {
730
- const parsedChunk = JSON.parse(chunk);
731
- yield parsedChunk;
732
- } catch {
733
- }
734
- }
735
- }
736
- }
737
- } catch {
738
- }
739
- }
740
- if (buffer) {
741
- try {
742
- yield JSON.parse(buffer);
743
- } catch {
744
- }
745
- }
746
- } finally {
747
- reader.cancel().catch(() => {
748
- });
749
- }
750
- }
751
- /**
752
- * Watches legacy workflow transitions in real-time
753
- * @param runId - Optional run ID to filter the watch stream
754
- * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
755
- */
756
- async watch({ runId }, onRecord) {
757
- const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
758
- stream: true
759
- });
760
- if (!response.ok) {
761
- throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
762
- }
763
- if (!response.body) {
764
- throw new Error("Response body is null");
765
- }
766
- for await (const record of this.streamProcessor(response.body)) {
767
- onRecord(record);
768
- }
769
- }
770
- };
771
-
772
- // src/resources/tool.ts
773
- var Tool = class extends BaseResource {
774
- constructor(options, toolId) {
775
- super(options);
776
- this.toolId = toolId;
777
- }
778
- /**
779
- * Retrieves details about the tool
780
- * @returns Promise containing tool details including description and schemas
781
- */
782
- details() {
783
- return this.request(`/api/tools/${this.toolId}`);
784
- }
785
- /**
786
- * Executes the tool with the provided parameters
787
- * @param params - Parameters required for tool execution
788
- * @returns Promise containing the tool execution results
789
- */
790
- execute(params) {
791
- const url = new URLSearchParams();
792
- if (params.runId) {
793
- url.set("runId", params.runId);
794
- }
795
- const body = {
796
- data: params.data,
797
- runtimeContext: parseClientRuntimeContext(params.runtimeContext)
798
- };
799
- return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
800
- method: "POST",
801
- body
802
- });
803
- }
804
- };
805
-
806
- // src/resources/workflow.ts
807
- var RECORD_SEPARATOR2 = "";
808
- var Workflow = class extends BaseResource {
809
- constructor(options, workflowId) {
810
- super(options);
811
- this.workflowId = workflowId;
1540
+ }
1541
+ };
1542
+
1543
+ // src/resources/workflow.ts
1544
+ var RECORD_SEPARATOR = "";
1545
+ var Workflow = class extends BaseResource {
1546
+ constructor(options, workflowId) {
1547
+ super(options);
1548
+ this.workflowId = workflowId;
812
1549
  }
813
1550
  /**
814
1551
  * Creates an async generator that processes a readable stream and yields workflow records
@@ -828,7 +1565,7 @@ var Workflow = class extends BaseResource {
828
1565
  if (done && !value) continue;
829
1566
  try {
830
1567
  const decoded = value ? new TextDecoder().decode(value) : "";
831
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1568
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
832
1569
  buffer = chunks.pop() || "";
833
1570
  for (const chunk of chunks) {
834
1571
  if (chunk) {
@@ -857,17 +1594,20 @@ var Workflow = class extends BaseResource {
857
1594
  }
858
1595
  /**
859
1596
  * Retrieves details about the workflow
1597
+ * @param runtimeContext - Optional runtime context to pass as query parameter
860
1598
  * @returns Promise containing workflow details including steps and graphs
861
1599
  */
862
- details() {
863
- return this.request(`/api/workflows/${this.workflowId}`);
1600
+ details(runtimeContext) {
1601
+ return this.request(`/api/workflows/${this.workflowId}${runtimeContextQueryString(runtimeContext)}`);
864
1602
  }
865
1603
  /**
866
1604
  * Retrieves all runs for a workflow
867
1605
  * @param params - Parameters for filtering runs
1606
+ * @param runtimeContext - Optional runtime context to pass as query parameter
868
1607
  * @returns Promise containing workflow runs array
869
1608
  */
870
- runs(params) {
1609
+ runs(params, runtimeContext) {
1610
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
871
1611
  const searchParams = new URLSearchParams();
872
1612
  if (params?.fromDate) {
873
1613
  searchParams.set("fromDate", params.fromDate.toISOString());
@@ -875,34 +1615,120 @@ var Workflow = class extends BaseResource {
875
1615
  if (params?.toDate) {
876
1616
  searchParams.set("toDate", params.toDate.toISOString());
877
1617
  }
878
- if (params?.limit) {
1618
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
879
1619
  searchParams.set("limit", String(params.limit));
880
1620
  }
881
- if (params?.offset) {
1621
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
882
1622
  searchParams.set("offset", String(params.offset));
883
1623
  }
884
1624
  if (params?.resourceId) {
885
1625
  searchParams.set("resourceId", params.resourceId);
886
1626
  }
1627
+ if (runtimeContextParam) {
1628
+ searchParams.set("runtimeContext", runtimeContextParam);
1629
+ }
887
1630
  if (searchParams.size) {
888
1631
  return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
889
1632
  } else {
890
1633
  return this.request(`/api/workflows/${this.workflowId}/runs`);
891
1634
  }
892
1635
  }
1636
+ /**
1637
+ * Retrieves a specific workflow run by its ID
1638
+ * @param runId - The ID of the workflow run to retrieve
1639
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1640
+ * @returns Promise containing the workflow run details
1641
+ */
1642
+ runById(runId, runtimeContext) {
1643
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}${runtimeContextQueryString(runtimeContext)}`);
1644
+ }
1645
+ /**
1646
+ * Retrieves the execution result for a specific workflow run by its ID
1647
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1648
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1649
+ * @returns Promise containing the workflow run execution result
1650
+ */
1651
+ runExecutionResult(runId, runtimeContext) {
1652
+ return this.request(
1653
+ `/api/workflows/${this.workflowId}/runs/${runId}/execution-result${runtimeContextQueryString(runtimeContext)}`
1654
+ );
1655
+ }
1656
+ /**
1657
+ * Cancels a specific workflow run by its ID
1658
+ * @param runId - The ID of the workflow run to cancel
1659
+ * @returns Promise containing a success message
1660
+ */
1661
+ cancelRun(runId) {
1662
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1663
+ method: "POST"
1664
+ });
1665
+ }
1666
+ /**
1667
+ * Sends an event to a specific workflow run by its ID
1668
+ * @param params - Object containing the runId, event and data
1669
+ * @returns Promise containing a success message
1670
+ */
1671
+ sendRunEvent(params) {
1672
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1673
+ method: "POST",
1674
+ body: { event: params.event, data: params.data }
1675
+ });
1676
+ }
1677
+ /**
1678
+ * @deprecated Use createRunAsync() instead.
1679
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
1680
+ */
1681
+ async createRun(_params) {
1682
+ throw new Error(
1683
+ "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."
1684
+ );
1685
+ }
893
1686
  /**
894
1687
  * Creates a new workflow run
895
1688
  * @param params - Optional object containing the optional runId
896
- * @returns Promise containing the runId of the created run
1689
+ * @returns Promise containing the runId of the created run with methods to control execution
897
1690
  */
898
- createRun(params) {
1691
+ async createRunAsync(params) {
899
1692
  const searchParams = new URLSearchParams();
900
1693
  if (!!params?.runId) {
901
1694
  searchParams.set("runId", params.runId);
902
1695
  }
903
- return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
904
- method: "POST"
905
- });
1696
+ const res = await this.request(
1697
+ `/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`,
1698
+ {
1699
+ method: "POST"
1700
+ }
1701
+ );
1702
+ const runId = res.runId;
1703
+ return {
1704
+ runId,
1705
+ start: async (p) => {
1706
+ return this.start({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1707
+ },
1708
+ startAsync: async (p) => {
1709
+ return this.startAsync({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1710
+ },
1711
+ watch: async (onRecord) => {
1712
+ return this.watch({ runId }, onRecord);
1713
+ },
1714
+ stream: async (p) => {
1715
+ return this.stream({ runId, inputData: p.inputData, runtimeContext: p.runtimeContext });
1716
+ },
1717
+ resume: async (p) => {
1718
+ return this.resume({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1719
+ },
1720
+ resumeAsync: async (p) => {
1721
+ return this.resumeAsync({ runId, step: p.step, resumeData: p.resumeData, runtimeContext: p.runtimeContext });
1722
+ },
1723
+ resumeStreamVNext: async (p) => {
1724
+ return this.resumeStreamVNext({
1725
+ runId,
1726
+ step: p.step,
1727
+ resumeData: p.resumeData,
1728
+ runtimeContext: p.runtimeContext
1729
+ });
1730
+ }
1731
+ };
906
1732
  }
907
1733
  /**
908
1734
  * Starts a workflow run synchronously without waiting for the workflow to complete
@@ -930,7 +1756,6 @@ var Workflow = class extends BaseResource {
930
1756
  const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
931
1757
  return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
932
1758
  method: "POST",
933
- stream: true,
934
1759
  body: {
935
1760
  step,
936
1761
  resumeData,
@@ -955,16 +1780,16 @@ var Workflow = class extends BaseResource {
955
1780
  });
956
1781
  }
957
1782
  /**
958
- * Starts a vNext workflow run and returns a stream
1783
+ * Starts a workflow run and returns a stream
959
1784
  * @param params - Object containing the optional runId, inputData and runtimeContext
960
- * @returns Promise containing the vNext workflow execution results
1785
+ * @returns Promise containing the workflow execution results
961
1786
  */
962
1787
  async stream(params) {
963
1788
  const searchParams = new URLSearchParams();
964
1789
  if (!!params?.runId) {
965
1790
  searchParams.set("runId", params.runId);
966
1791
  }
967
- const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1792
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
968
1793
  const response = await this.request(
969
1794
  `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
970
1795
  {
@@ -973,25 +1798,127 @@ var Workflow = class extends BaseResource {
973
1798
  stream: true
974
1799
  }
975
1800
  );
1801
+ if (!response.ok) {
1802
+ throw new Error(`Failed to stream workflow: ${response.statusText}`);
1803
+ }
1804
+ if (!response.body) {
1805
+ throw new Error("Response body is null");
1806
+ }
1807
+ let failedChunk = void 0;
1808
+ const transformStream = new TransformStream({
1809
+ start() {
1810
+ },
1811
+ async transform(chunk, controller) {
1812
+ try {
1813
+ const decoded = new TextDecoder().decode(chunk);
1814
+ const chunks = decoded.split(RECORD_SEPARATOR);
1815
+ for (const chunk2 of chunks) {
1816
+ if (chunk2) {
1817
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1818
+ try {
1819
+ const parsedChunk = JSON.parse(newChunk);
1820
+ controller.enqueue(parsedChunk);
1821
+ failedChunk = void 0;
1822
+ } catch {
1823
+ failedChunk = newChunk;
1824
+ }
1825
+ }
1826
+ }
1827
+ } catch {
1828
+ }
1829
+ }
1830
+ });
1831
+ return response.body.pipeThrough(transformStream);
1832
+ }
1833
+ /**
1834
+ * Observes workflow stream for a workflow run
1835
+ * @param params - Object containing the runId
1836
+ * @returns Promise containing the workflow execution results
1837
+ */
1838
+ async observeStream(params) {
1839
+ const searchParams = new URLSearchParams();
1840
+ searchParams.set("runId", params.runId);
1841
+ const response = await this.request(
1842
+ `/api/workflows/${this.workflowId}/observe-stream?${searchParams.toString()}`,
1843
+ {
1844
+ method: "POST",
1845
+ stream: true
1846
+ }
1847
+ );
1848
+ if (!response.ok) {
1849
+ throw new Error(`Failed to observe workflow stream: ${response.statusText}`);
1850
+ }
1851
+ if (!response.body) {
1852
+ throw new Error("Response body is null");
1853
+ }
1854
+ let failedChunk = void 0;
1855
+ const transformStream = new TransformStream({
1856
+ start() {
1857
+ },
1858
+ async transform(chunk, controller) {
1859
+ try {
1860
+ const decoded = new TextDecoder().decode(chunk);
1861
+ const chunks = decoded.split(RECORD_SEPARATOR);
1862
+ for (const chunk2 of chunks) {
1863
+ if (chunk2) {
1864
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1865
+ try {
1866
+ const parsedChunk = JSON.parse(newChunk);
1867
+ controller.enqueue(parsedChunk);
1868
+ failedChunk = void 0;
1869
+ } catch {
1870
+ failedChunk = newChunk;
1871
+ }
1872
+ }
1873
+ }
1874
+ } catch {
1875
+ }
1876
+ }
1877
+ });
1878
+ return response.body.pipeThrough(transformStream);
1879
+ }
1880
+ /**
1881
+ * Starts a workflow run and returns a stream
1882
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1883
+ * @returns Promise containing the workflow execution results
1884
+ */
1885
+ async streamVNext(params) {
1886
+ const searchParams = new URLSearchParams();
1887
+ if (!!params?.runId) {
1888
+ searchParams.set("runId", params.runId);
1889
+ }
1890
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1891
+ const response = await this.request(
1892
+ `/api/workflows/${this.workflowId}/streamVNext?${searchParams.toString()}`,
1893
+ {
1894
+ method: "POST",
1895
+ body: { inputData: params.inputData, runtimeContext, closeOnSuspend: params.closeOnSuspend },
1896
+ stream: true
1897
+ }
1898
+ );
976
1899
  if (!response.ok) {
977
1900
  throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
978
1901
  }
979
1902
  if (!response.body) {
980
1903
  throw new Error("Response body is null");
981
1904
  }
1905
+ let failedChunk = void 0;
982
1906
  const transformStream = new TransformStream({
983
1907
  start() {
984
1908
  },
985
1909
  async transform(chunk, controller) {
986
1910
  try {
987
1911
  const decoded = new TextDecoder().decode(chunk);
988
- const chunks = decoded.split(RECORD_SEPARATOR2);
1912
+ const chunks = decoded.split(RECORD_SEPARATOR);
989
1913
  for (const chunk2 of chunks) {
990
1914
  if (chunk2) {
1915
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
991
1916
  try {
992
- const parsedChunk = JSON.parse(chunk2);
1917
+ const parsedChunk = JSON.parse(newChunk);
993
1918
  controller.enqueue(parsedChunk);
1919
+ failedChunk = void 0;
994
1920
  } catch {
1921
+ failedChunk = newChunk;
995
1922
  }
996
1923
  }
997
1924
  }
@@ -1018,22 +1945,42 @@ var Workflow = class extends BaseResource {
1018
1945
  });
1019
1946
  }
1020
1947
  /**
1021
- * Watches workflow transitions in real-time
1022
- * @param runId - Optional run ID to filter the watch stream
1023
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1948
+ * Resumes a suspended workflow step that uses streamVNext asynchronously and returns a promise that resolves when the workflow is complete
1949
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1950
+ * @returns Promise containing the workflow resume results
1024
1951
  */
1025
- async watch({ runId }, onRecord) {
1026
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1027
- stream: true
1028
- });
1029
- if (!response.ok) {
1952
+ resumeStreamVNext(params) {
1953
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1954
+ return this.request(`/api/workflows/${this.workflowId}/resume-stream?runId=${params.runId}`, {
1955
+ method: "POST",
1956
+ body: {
1957
+ step: params.step,
1958
+ resumeData: params.resumeData,
1959
+ runtimeContext
1960
+ }
1961
+ });
1962
+ }
1963
+ /**
1964
+ * Watches workflow transitions in real-time
1965
+ * @param runId - Optional run ID to filter the watch stream
1966
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1967
+ */
1968
+ async watch({ runId }, onRecord) {
1969
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1970
+ stream: true
1971
+ });
1972
+ if (!response.ok) {
1030
1973
  throw new Error(`Failed to watch workflow: ${response.statusText}`);
1031
1974
  }
1032
1975
  if (!response.body) {
1033
1976
  throw new Error("Response body is null");
1034
1977
  }
1035
1978
  for await (const record of this.streamProcessor(response.body)) {
1036
- onRecord(record);
1979
+ if (typeof record === "string") {
1980
+ onRecord(JSON.parse(record));
1981
+ } else {
1982
+ onRecord(record);
1983
+ }
1037
1984
  }
1038
1985
  }
1039
1986
  /**
@@ -1049,7 +1996,7 @@ var Workflow = class extends BaseResource {
1049
1996
  async start(controller) {
1050
1997
  try {
1051
1998
  for await (const record of records) {
1052
- const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1999
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
1053
2000
  controller.enqueue(encoder.encode(json));
1054
2001
  }
1055
2002
  controller.close();
@@ -1072,129 +2019,753 @@ var A2A = class extends BaseResource {
1072
2019
  * @returns Promise containing the agent card information
1073
2020
  */
1074
2021
  async getCard() {
1075
- return this.request(`/.well-known/${this.agentId}/agent.json`);
2022
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
1076
2023
  }
1077
2024
  /**
1078
- * Send a message to the agent and get a response
2025
+ * Send a message to the agent and gets a message or task response
1079
2026
  * @param params - Parameters for the task
1080
- * @returns Promise containing the task response
2027
+ * @returns Promise containing the response
1081
2028
  */
1082
2029
  async sendMessage(params) {
1083
2030
  const response = await this.request(`/a2a/${this.agentId}`, {
1084
2031
  method: "POST",
1085
2032
  body: {
1086
- method: "tasks/send",
2033
+ method: "message/send",
2034
+ params
2035
+ }
2036
+ });
2037
+ return response;
2038
+ }
2039
+ /**
2040
+ * Sends a message to an agent to initiate/continue a task and subscribes
2041
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
2042
+ * @param params - Parameters for the task
2043
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
2044
+ */
2045
+ async sendStreamingMessage(params) {
2046
+ const response = await this.request(`/a2a/${this.agentId}`, {
2047
+ method: "POST",
2048
+ body: {
2049
+ method: "message/stream",
2050
+ params
2051
+ }
2052
+ });
2053
+ return response;
2054
+ }
2055
+ /**
2056
+ * Get the status and result of a task
2057
+ * @param params - Parameters for querying the task
2058
+ * @returns Promise containing the task response
2059
+ */
2060
+ async getTask(params) {
2061
+ const response = await this.request(`/a2a/${this.agentId}`, {
2062
+ method: "POST",
2063
+ body: {
2064
+ method: "tasks/get",
1087
2065
  params
1088
2066
  }
1089
- });
1090
- return { task: response.result };
1091
- }
1092
- /**
1093
- * Get the status and result of a task
1094
- * @param params - Parameters for querying the task
1095
- * @returns Promise containing the task response
1096
- */
1097
- async getTask(params) {
1098
- const response = await this.request(`/a2a/${this.agentId}`, {
1099
- method: "POST",
1100
- body: {
1101
- method: "tasks/get",
1102
- params
2067
+ });
2068
+ return response;
2069
+ }
2070
+ /**
2071
+ * Cancel a running task
2072
+ * @param params - Parameters identifying the task to cancel
2073
+ * @returns Promise containing the task response
2074
+ */
2075
+ async cancelTask(params) {
2076
+ return this.request(`/a2a/${this.agentId}`, {
2077
+ method: "POST",
2078
+ body: {
2079
+ method: "tasks/cancel",
2080
+ params
2081
+ }
2082
+ });
2083
+ }
2084
+ };
2085
+
2086
+ // src/resources/mcp-tool.ts
2087
+ var MCPTool = class extends BaseResource {
2088
+ serverId;
2089
+ toolId;
2090
+ constructor(options, serverId, toolId) {
2091
+ super(options);
2092
+ this.serverId = serverId;
2093
+ this.toolId = toolId;
2094
+ }
2095
+ /**
2096
+ * Retrieves details about this specific tool from the MCP server.
2097
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2098
+ * @returns Promise containing the tool's information (name, description, schema).
2099
+ */
2100
+ details(runtimeContext) {
2101
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}${runtimeContextQueryString(runtimeContext)}`);
2102
+ }
2103
+ /**
2104
+ * Executes this specific tool on the MCP server.
2105
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
2106
+ * @returns Promise containing the result of the tool execution.
2107
+ */
2108
+ execute(params) {
2109
+ const body = {};
2110
+ if (params.data !== void 0) body.data = params.data;
2111
+ if (params.runtimeContext !== void 0) {
2112
+ body.runtimeContext = params.runtimeContext;
2113
+ }
2114
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
2115
+ method: "POST",
2116
+ body: Object.keys(body).length > 0 ? body : void 0
2117
+ });
2118
+ }
2119
+ };
2120
+
2121
+ // src/resources/agent-builder.ts
2122
+ var RECORD_SEPARATOR2 = "";
2123
+ var AgentBuilder = class extends BaseResource {
2124
+ constructor(options, actionId) {
2125
+ super(options);
2126
+ this.actionId = actionId;
2127
+ }
2128
+ // Helper function to transform workflow result to action result
2129
+ transformWorkflowResult(result) {
2130
+ if (result.status === "success") {
2131
+ return {
2132
+ success: result.result.success || false,
2133
+ applied: result.result.applied || false,
2134
+ branchName: result.result.branchName,
2135
+ message: result.result.message || "Agent builder action completed",
2136
+ validationResults: result.result.validationResults,
2137
+ error: result.result.error,
2138
+ errors: result.result.errors,
2139
+ stepResults: result.result.stepResults
2140
+ };
2141
+ } else if (result.status === "failed") {
2142
+ return {
2143
+ success: false,
2144
+ applied: false,
2145
+ message: `Agent builder action failed: ${result.error.message}`,
2146
+ error: result.error.message
2147
+ };
2148
+ } else {
2149
+ return {
2150
+ success: false,
2151
+ applied: false,
2152
+ message: "Agent builder action was suspended",
2153
+ error: "Workflow suspended - manual intervention required"
2154
+ };
2155
+ }
2156
+ }
2157
+ /**
2158
+ * @deprecated Use createRunAsync() instead.
2159
+ * @throws {Error} Always throws an error directing users to use createRunAsync()
2160
+ */
2161
+ async createRun(_params) {
2162
+ throw new Error(
2163
+ "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."
2164
+ );
2165
+ }
2166
+ /**
2167
+ * Creates a new agent builder action run and returns the runId.
2168
+ * This calls `/api/agent-builder/:actionId/create-run`.
2169
+ */
2170
+ async createRunAsync(params) {
2171
+ const searchParams = new URLSearchParams();
2172
+ if (!!params?.runId) {
2173
+ searchParams.set("runId", params.runId);
2174
+ }
2175
+ const url = `/api/agent-builder/${this.actionId}/create-run${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2176
+ return this.request(url, {
2177
+ method: "POST"
2178
+ });
2179
+ }
2180
+ /**
2181
+ * Starts agent builder action asynchronously and waits for completion.
2182
+ * This calls `/api/agent-builder/:actionId/start-async`.
2183
+ */
2184
+ async startAsync(params, runId) {
2185
+ const searchParams = new URLSearchParams();
2186
+ if (runId) {
2187
+ searchParams.set("runId", runId);
2188
+ }
2189
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2190
+ const { runtimeContext: _, ...actionParams } = params;
2191
+ const url = `/api/agent-builder/${this.actionId}/start-async${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2192
+ const result = await this.request(url, {
2193
+ method: "POST",
2194
+ body: { ...actionParams, runtimeContext }
2195
+ });
2196
+ return this.transformWorkflowResult(result);
2197
+ }
2198
+ /**
2199
+ * Starts an existing agent builder action run.
2200
+ * This calls `/api/agent-builder/:actionId/start`.
2201
+ */
2202
+ async startActionRun(params, runId) {
2203
+ const searchParams = new URLSearchParams();
2204
+ searchParams.set("runId", runId);
2205
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2206
+ const { runtimeContext: _, ...actionParams } = params;
2207
+ const url = `/api/agent-builder/${this.actionId}/start?${searchParams.toString()}`;
2208
+ return this.request(url, {
2209
+ method: "POST",
2210
+ body: { ...actionParams, runtimeContext }
2211
+ });
2212
+ }
2213
+ /**
2214
+ * Resumes a suspended agent builder action step.
2215
+ * This calls `/api/agent-builder/:actionId/resume`.
2216
+ */
2217
+ async resume(params, runId) {
2218
+ const searchParams = new URLSearchParams();
2219
+ searchParams.set("runId", runId);
2220
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2221
+ const { runtimeContext: _, ...resumeParams } = params;
2222
+ const url = `/api/agent-builder/${this.actionId}/resume?${searchParams.toString()}`;
2223
+ return this.request(url, {
2224
+ method: "POST",
2225
+ body: { ...resumeParams, runtimeContext }
2226
+ });
2227
+ }
2228
+ /**
2229
+ * Resumes a suspended agent builder action step asynchronously.
2230
+ * This calls `/api/agent-builder/:actionId/resume-async`.
2231
+ */
2232
+ async resumeAsync(params, runId) {
2233
+ const searchParams = new URLSearchParams();
2234
+ searchParams.set("runId", runId);
2235
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2236
+ const { runtimeContext: _, ...resumeParams } = params;
2237
+ const url = `/api/agent-builder/${this.actionId}/resume-async?${searchParams.toString()}`;
2238
+ const result = await this.request(url, {
2239
+ method: "POST",
2240
+ body: { ...resumeParams, runtimeContext }
2241
+ });
2242
+ return this.transformWorkflowResult(result);
2243
+ }
2244
+ /**
2245
+ * Creates an async generator that processes a readable stream and yields action records
2246
+ * separated by the Record Separator character (\x1E)
2247
+ *
2248
+ * @param stream - The readable stream to process
2249
+ * @returns An async generator that yields parsed records
2250
+ */
2251
+ async *streamProcessor(stream) {
2252
+ const reader = stream.getReader();
2253
+ let doneReading = false;
2254
+ let buffer = "";
2255
+ try {
2256
+ while (!doneReading) {
2257
+ const { done, value } = await reader.read();
2258
+ doneReading = done;
2259
+ if (done && !value) continue;
2260
+ try {
2261
+ const decoded = value ? new TextDecoder().decode(value) : "";
2262
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
2263
+ buffer = chunks.pop() || "";
2264
+ for (const chunk of chunks) {
2265
+ if (chunk) {
2266
+ if (typeof chunk === "string") {
2267
+ try {
2268
+ const parsedChunk = JSON.parse(chunk);
2269
+ yield parsedChunk;
2270
+ } catch {
2271
+ }
2272
+ }
2273
+ }
2274
+ }
2275
+ } catch {
2276
+ }
2277
+ }
2278
+ if (buffer) {
2279
+ try {
2280
+ yield JSON.parse(buffer);
2281
+ } catch {
2282
+ }
2283
+ }
2284
+ } finally {
2285
+ reader.cancel().catch(() => {
2286
+ });
2287
+ }
2288
+ }
2289
+ /**
2290
+ * Streams agent builder action progress in real-time.
2291
+ * This calls `/api/agent-builder/:actionId/stream`.
2292
+ */
2293
+ async stream(params, runId) {
2294
+ const searchParams = new URLSearchParams();
2295
+ if (runId) {
2296
+ searchParams.set("runId", runId);
2297
+ }
2298
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2299
+ const { runtimeContext: _, ...actionParams } = params;
2300
+ const url = `/api/agent-builder/${this.actionId}/stream${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2301
+ const response = await this.request(url, {
2302
+ method: "POST",
2303
+ body: { ...actionParams, runtimeContext },
2304
+ stream: true
2305
+ });
2306
+ if (!response.ok) {
2307
+ throw new Error(`Failed to stream agent builder action: ${response.statusText}`);
2308
+ }
2309
+ if (!response.body) {
2310
+ throw new Error("Response body is null");
2311
+ }
2312
+ let failedChunk = void 0;
2313
+ const transformStream = new TransformStream({
2314
+ start() {
2315
+ },
2316
+ async transform(chunk, controller) {
2317
+ try {
2318
+ const decoded = new TextDecoder().decode(chunk);
2319
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2320
+ for (const chunk2 of chunks) {
2321
+ if (chunk2) {
2322
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2323
+ try {
2324
+ const parsedChunk = JSON.parse(newChunk);
2325
+ controller.enqueue(parsedChunk);
2326
+ failedChunk = void 0;
2327
+ } catch {
2328
+ failedChunk = newChunk;
2329
+ }
2330
+ }
2331
+ }
2332
+ } catch {
2333
+ }
2334
+ }
2335
+ });
2336
+ return response.body.pipeThrough(transformStream);
2337
+ }
2338
+ /**
2339
+ * Streams agent builder action progress in real-time using VNext streaming.
2340
+ * This calls `/api/agent-builder/:actionId/streamVNext`.
2341
+ */
2342
+ async streamVNext(params, runId) {
2343
+ const searchParams = new URLSearchParams();
2344
+ if (runId) {
2345
+ searchParams.set("runId", runId);
2346
+ }
2347
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
2348
+ const { runtimeContext: _, ...actionParams } = params;
2349
+ const url = `/api/agent-builder/${this.actionId}/streamVNext${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2350
+ const response = await this.request(url, {
2351
+ method: "POST",
2352
+ body: { ...actionParams, runtimeContext },
2353
+ stream: true
2354
+ });
2355
+ if (!response.ok) {
2356
+ throw new Error(`Failed to stream agent builder action VNext: ${response.statusText}`);
2357
+ }
2358
+ if (!response.body) {
2359
+ throw new Error("Response body is null");
2360
+ }
2361
+ let failedChunk = void 0;
2362
+ const transformStream = new TransformStream({
2363
+ start() {
2364
+ },
2365
+ async transform(chunk, controller) {
2366
+ try {
2367
+ const decoded = new TextDecoder().decode(chunk);
2368
+ const chunks = decoded.split(RECORD_SEPARATOR2);
2369
+ for (const chunk2 of chunks) {
2370
+ if (chunk2) {
2371
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
2372
+ try {
2373
+ const parsedChunk = JSON.parse(newChunk);
2374
+ controller.enqueue(parsedChunk);
2375
+ failedChunk = void 0;
2376
+ } catch {
2377
+ failedChunk = newChunk;
2378
+ }
2379
+ }
2380
+ }
2381
+ } catch {
2382
+ }
2383
+ }
2384
+ });
2385
+ return response.body.pipeThrough(transformStream);
2386
+ }
2387
+ /**
2388
+ * Watches an existing agent builder action run by runId.
2389
+ * This is used for hot reload recovery - it loads the existing run state
2390
+ * and streams any remaining progress.
2391
+ * This calls `/api/agent-builder/:actionId/watch`.
2392
+ */
2393
+ async watch({ runId, eventType }, onRecord) {
2394
+ const url = `/api/agent-builder/${this.actionId}/watch?runId=${runId}${eventType ? `&eventType=${eventType}` : ""}`;
2395
+ const response = await this.request(url, {
2396
+ method: "GET",
2397
+ stream: true
2398
+ });
2399
+ if (!response.ok) {
2400
+ throw new Error(`Failed to watch agent builder action: ${response.statusText}`);
2401
+ }
2402
+ if (!response.body) {
2403
+ throw new Error("Response body is null");
2404
+ }
2405
+ for await (const record of this.streamProcessor(response.body)) {
2406
+ if (typeof record === "string") {
2407
+ onRecord(JSON.parse(record));
2408
+ } else {
2409
+ onRecord(record);
2410
+ }
2411
+ }
2412
+ }
2413
+ /**
2414
+ * Gets a specific action run by its ID.
2415
+ * This calls `/api/agent-builder/:actionId/runs/:runId`.
2416
+ */
2417
+ async runById(runId) {
2418
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}`;
2419
+ return this.request(url, {
2420
+ method: "GET"
2421
+ });
2422
+ }
2423
+ /**
2424
+ * Gets details about this agent builder action.
2425
+ * This calls `/api/agent-builder/:actionId`.
2426
+ */
2427
+ async details() {
2428
+ const result = await this.request(`/api/agent-builder/${this.actionId}`);
2429
+ return result;
2430
+ }
2431
+ /**
2432
+ * Gets all runs for this agent builder action.
2433
+ * This calls `/api/agent-builder/:actionId/runs`.
2434
+ */
2435
+ async runs(params) {
2436
+ const searchParams = new URLSearchParams();
2437
+ if (params?.fromDate) {
2438
+ searchParams.set("fromDate", params.fromDate.toISOString());
2439
+ }
2440
+ if (params?.toDate) {
2441
+ searchParams.set("toDate", params.toDate.toISOString());
2442
+ }
2443
+ if (params?.limit !== void 0) {
2444
+ searchParams.set("limit", String(params.limit));
2445
+ }
2446
+ if (params?.offset !== void 0) {
2447
+ searchParams.set("offset", String(params.offset));
2448
+ }
2449
+ if (params?.resourceId) {
2450
+ searchParams.set("resourceId", params.resourceId);
2451
+ }
2452
+ const url = `/api/agent-builder/${this.actionId}/runs${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
2453
+ return this.request(url, {
2454
+ method: "GET"
2455
+ });
2456
+ }
2457
+ /**
2458
+ * Gets the execution result of an agent builder action run.
2459
+ * This calls `/api/agent-builder/:actionId/runs/:runId/execution-result`.
2460
+ */
2461
+ async runExecutionResult(runId) {
2462
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/execution-result`;
2463
+ return this.request(url, {
2464
+ method: "GET"
2465
+ });
2466
+ }
2467
+ /**
2468
+ * Cancels an agent builder action run.
2469
+ * This calls `/api/agent-builder/:actionId/runs/:runId/cancel`.
2470
+ */
2471
+ async cancelRun(runId) {
2472
+ const url = `/api/agent-builder/${this.actionId}/runs/${runId}/cancel`;
2473
+ return this.request(url, {
2474
+ method: "POST"
2475
+ });
2476
+ }
2477
+ /**
2478
+ * Sends an event to an agent builder action run.
2479
+ * This calls `/api/agent-builder/:actionId/runs/:runId/send-event`.
2480
+ */
2481
+ async sendRunEvent(params) {
2482
+ const url = `/api/agent-builder/${this.actionId}/runs/${params.runId}/send-event`;
2483
+ return this.request(url, {
2484
+ method: "POST",
2485
+ body: { event: params.event, data: params.data }
2486
+ });
2487
+ }
2488
+ };
2489
+
2490
+ // src/resources/observability.ts
2491
+ var Observability = class extends BaseResource {
2492
+ constructor(options) {
2493
+ super(options);
2494
+ }
2495
+ /**
2496
+ * Retrieves a specific AI trace by ID
2497
+ * @param traceId - ID of the trace to retrieve
2498
+ * @returns Promise containing the AI trace with all its spans
2499
+ */
2500
+ getTrace(traceId) {
2501
+ return this.request(`/api/observability/traces/${traceId}`);
2502
+ }
2503
+ /**
2504
+ * Retrieves paginated list of AI traces with optional filtering
2505
+ * @param params - Parameters for pagination and filtering
2506
+ * @returns Promise containing paginated traces and pagination info
2507
+ */
2508
+ getTraces(params) {
2509
+ const { pagination, filters } = params;
2510
+ const { page, perPage, dateRange } = pagination || {};
2511
+ const { name, spanType, entityId, entityType } = filters || {};
2512
+ const searchParams = new URLSearchParams();
2513
+ if (page !== void 0) {
2514
+ searchParams.set("page", String(page));
2515
+ }
2516
+ if (perPage !== void 0) {
2517
+ searchParams.set("perPage", String(perPage));
2518
+ }
2519
+ if (name) {
2520
+ searchParams.set("name", name);
2521
+ }
2522
+ if (spanType !== void 0) {
2523
+ searchParams.set("spanType", String(spanType));
2524
+ }
2525
+ if (entityId && entityType) {
2526
+ searchParams.set("entityId", entityId);
2527
+ searchParams.set("entityType", entityType);
2528
+ }
2529
+ if (dateRange) {
2530
+ const dateRangeStr = JSON.stringify({
2531
+ start: dateRange.start instanceof Date ? dateRange.start.toISOString() : dateRange.start,
2532
+ end: dateRange.end instanceof Date ? dateRange.end.toISOString() : dateRange.end
2533
+ });
2534
+ searchParams.set("dateRange", dateRangeStr);
2535
+ }
2536
+ const queryString = searchParams.toString();
2537
+ return this.request(`/api/observability/traces${queryString ? `?${queryString}` : ""}`);
2538
+ }
2539
+ score(params) {
2540
+ return this.request(`/api/observability/traces/score`, {
2541
+ method: "POST",
2542
+ body: { ...params }
2543
+ });
2544
+ }
2545
+ };
2546
+
2547
+ // src/resources/network-memory-thread.ts
2548
+ var NetworkMemoryThread = class extends BaseResource {
2549
+ constructor(options, threadId, networkId) {
2550
+ super(options);
2551
+ this.threadId = threadId;
2552
+ this.networkId = networkId;
2553
+ }
2554
+ /**
2555
+ * Retrieves the memory thread details
2556
+ * @returns Promise containing thread details including title and metadata
2557
+ */
2558
+ get() {
2559
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
2560
+ }
2561
+ /**
2562
+ * Updates the memory thread properties
2563
+ * @param params - Update parameters including title and metadata
2564
+ * @returns Promise containing updated thread details
2565
+ */
2566
+ update(params) {
2567
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2568
+ method: "PATCH",
2569
+ body: params
2570
+ });
2571
+ }
2572
+ /**
2573
+ * Deletes the memory thread
2574
+ * @returns Promise containing deletion result
2575
+ */
2576
+ delete() {
2577
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
2578
+ method: "DELETE"
2579
+ });
2580
+ }
2581
+ /**
2582
+ * Retrieves messages associated with the thread
2583
+ * @param params - Optional parameters including limit for number of messages to retrieve
2584
+ * @returns Promise containing thread messages and UI messages
2585
+ */
2586
+ getMessages(params) {
2587
+ const query = new URLSearchParams({
2588
+ networkId: this.networkId,
2589
+ ...params?.limit ? { limit: params.limit.toString() } : {}
2590
+ });
2591
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
2592
+ }
2593
+ /**
2594
+ * Deletes one or more messages from the thread
2595
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
2596
+ * message object with id property, or array of message objects
2597
+ * @returns Promise containing deletion result
2598
+ */
2599
+ deleteMessages(messageIds) {
2600
+ const query = new URLSearchParams({
2601
+ networkId: this.networkId
2602
+ });
2603
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
2604
+ method: "POST",
2605
+ body: { messageIds }
2606
+ });
2607
+ }
2608
+ };
2609
+
2610
+ // src/resources/vNextNetwork.ts
2611
+ var RECORD_SEPARATOR3 = "";
2612
+ var VNextNetwork = class extends BaseResource {
2613
+ constructor(options, networkId) {
2614
+ super(options);
2615
+ this.networkId = networkId;
2616
+ }
2617
+ /**
2618
+ * Retrieves details about the network
2619
+ * @param runtimeContext - Optional runtime context to pass as query parameter
2620
+ * @returns Promise containing vNext network details
2621
+ */
2622
+ details(runtimeContext) {
2623
+ return this.request(`/api/networks/v-next/${this.networkId}${runtimeContextQueryString(runtimeContext)}`);
2624
+ }
2625
+ /**
2626
+ * Generates a response from the v-next network
2627
+ * @param params - Generation parameters including message
2628
+ * @returns Promise containing the generated response
2629
+ */
2630
+ generate(params) {
2631
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
2632
+ method: "POST",
2633
+ body: {
2634
+ ...params,
2635
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2636
+ }
2637
+ });
2638
+ }
2639
+ /**
2640
+ * Generates a response from the v-next network using multiple primitives
2641
+ * @param params - Generation parameters including message
2642
+ * @returns Promise containing the generated response
2643
+ */
2644
+ loop(params) {
2645
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
2646
+ method: "POST",
2647
+ body: {
2648
+ ...params,
2649
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2650
+ }
2651
+ });
2652
+ }
2653
+ async *streamProcessor(stream) {
2654
+ const reader = stream.getReader();
2655
+ let doneReading = false;
2656
+ let buffer = "";
2657
+ try {
2658
+ while (!doneReading) {
2659
+ const { done, value } = await reader.read();
2660
+ doneReading = done;
2661
+ if (done && !value) continue;
2662
+ try {
2663
+ const decoded = value ? new TextDecoder().decode(value) : "";
2664
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
2665
+ buffer = chunks.pop() || "";
2666
+ for (const chunk of chunks) {
2667
+ if (chunk) {
2668
+ if (typeof chunk === "string") {
2669
+ try {
2670
+ const parsedChunk = JSON.parse(chunk);
2671
+ yield parsedChunk;
2672
+ } catch {
2673
+ }
2674
+ }
2675
+ }
2676
+ }
2677
+ } catch {
2678
+ }
2679
+ }
2680
+ if (buffer) {
2681
+ try {
2682
+ yield JSON.parse(buffer);
2683
+ } catch {
2684
+ }
1103
2685
  }
1104
- });
1105
- return response.result;
2686
+ } finally {
2687
+ reader.cancel().catch(() => {
2688
+ });
2689
+ }
1106
2690
  }
1107
2691
  /**
1108
- * Cancel a running task
1109
- * @param params - Parameters identifying the task to cancel
1110
- * @returns Promise containing the task response
2692
+ * Streams a response from the v-next network
2693
+ * @param params - Stream parameters including message
2694
+ * @returns Promise containing the results
1111
2695
  */
1112
- async cancelTask(params) {
1113
- return this.request(`/a2a/${this.agentId}`, {
2696
+ async stream(params, onRecord) {
2697
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1114
2698
  method: "POST",
1115
2699
  body: {
1116
- method: "tasks/cancel",
1117
- params
1118
- }
2700
+ ...params,
2701
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
2702
+ },
2703
+ stream: true
1119
2704
  });
2705
+ if (!response.ok) {
2706
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
2707
+ }
2708
+ if (!response.body) {
2709
+ throw new Error("Response body is null");
2710
+ }
2711
+ for await (const record of this.streamProcessor(response.body)) {
2712
+ if (typeof record === "string") {
2713
+ onRecord(JSON.parse(record));
2714
+ } else {
2715
+ onRecord(record);
2716
+ }
2717
+ }
1120
2718
  }
1121
2719
  /**
1122
- * Send a message and subscribe to streaming updates (not fully implemented)
1123
- * @param params - Parameters for the task
1124
- * @returns Promise containing the task response
2720
+ * Streams a response from the v-next network loop
2721
+ * @param params - Stream parameters including message
2722
+ * @returns Promise containing the results
1125
2723
  */
1126
- async sendAndSubscribe(params) {
1127
- return this.request(`/a2a/${this.agentId}`, {
2724
+ async loopStream(params, onRecord) {
2725
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1128
2726
  method: "POST",
1129
2727
  body: {
1130
- method: "tasks/sendSubscribe",
1131
- params
2728
+ ...params,
2729
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1132
2730
  },
1133
2731
  stream: true
1134
2732
  });
1135
- }
1136
- };
1137
-
1138
- // src/resources/mcp-tool.ts
1139
- var MCPTool = class extends BaseResource {
1140
- serverId;
1141
- toolId;
1142
- constructor(options, serverId, toolId) {
1143
- super(options);
1144
- this.serverId = serverId;
1145
- this.toolId = toolId;
1146
- }
1147
- /**
1148
- * Retrieves details about this specific tool from the MCP server.
1149
- * @returns Promise containing the tool's information (name, description, schema).
1150
- */
1151
- details() {
1152
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1153
- }
1154
- /**
1155
- * Executes this specific tool on the MCP server.
1156
- * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1157
- * @returns Promise containing the result of the tool execution.
1158
- */
1159
- execute(params) {
1160
- const body = {};
1161
- if (params.data !== void 0) body.data = params.data;
1162
- if (params.runtimeContext !== void 0) {
1163
- body.runtimeContext = params.runtimeContext;
2733
+ if (!response.ok) {
2734
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
2735
+ }
2736
+ if (!response.body) {
2737
+ throw new Error("Response body is null");
2738
+ }
2739
+ for await (const record of this.streamProcessor(response.body)) {
2740
+ if (typeof record === "string") {
2741
+ onRecord(JSON.parse(record));
2742
+ } else {
2743
+ onRecord(record);
2744
+ }
1164
2745
  }
1165
- return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1166
- method: "POST",
1167
- body: Object.keys(body).length > 0 ? body : void 0
1168
- });
1169
2746
  }
1170
2747
  };
1171
2748
 
1172
2749
  // src/client.ts
1173
2750
  var MastraClient = class extends BaseResource {
2751
+ observability;
1174
2752
  constructor(options) {
1175
2753
  super(options);
2754
+ this.observability = new Observability(options);
1176
2755
  }
1177
2756
  /**
1178
2757
  * Retrieves all available agents
2758
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1179
2759
  * @returns Promise containing map of agent IDs to agent details
1180
2760
  */
1181
- getAgents() {
1182
- return this.request("/api/agents");
1183
- }
1184
- async getAGUI({ resourceId }) {
1185
- const agents = await this.getAgents();
1186
- return Object.entries(agents).reduce(
1187
- (acc, [agentId]) => {
1188
- const agent = this.getAgent(agentId);
1189
- acc[agentId] = new AGUIAdapter({
1190
- agentId,
1191
- agent,
1192
- resourceId
1193
- });
1194
- return acc;
1195
- },
1196
- {}
1197
- );
2761
+ getAgents(runtimeContext) {
2762
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2763
+ const searchParams = new URLSearchParams();
2764
+ if (runtimeContextParam) {
2765
+ searchParams.set("runtimeContext", runtimeContextParam);
2766
+ }
2767
+ const queryString = searchParams.toString();
2768
+ return this.request(`/api/agents${queryString ? `?${queryString}` : ""}`);
1198
2769
  }
1199
2770
  /**
1200
2771
  * Gets an agent instance by ID
@@ -1212,6 +2783,14 @@ var MastraClient = class extends BaseResource {
1212
2783
  getMemoryThreads(params) {
1213
2784
  return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1214
2785
  }
2786
+ /**
2787
+ * Retrieves memory config for a resource
2788
+ * @param params - Parameters containing the resource ID
2789
+ * @returns Promise containing array of memory threads
2790
+ */
2791
+ getMemoryConfig(params) {
2792
+ return this.request(`/api/memory/config?agentId=${params.agentId}`);
2793
+ }
1215
2794
  /**
1216
2795
  * Creates a new memory thread
1217
2796
  * @param params - Parameters for creating the memory thread
@@ -1228,6 +2807,24 @@ var MastraClient = class extends BaseResource {
1228
2807
  getMemoryThread(threadId, agentId) {
1229
2808
  return new MemoryThread(this.options, threadId, agentId);
1230
2809
  }
2810
+ getThreadMessages(threadId, opts = {}) {
2811
+ let url = "";
2812
+ if (opts.agentId) {
2813
+ url = `/api/memory/threads/${threadId}/messages?agentId=${opts.agentId}`;
2814
+ } else if (opts.networkId) {
2815
+ url = `/api/memory/network/threads/${threadId}/messages?networkId=${opts.networkId}`;
2816
+ }
2817
+ return this.request(url);
2818
+ }
2819
+ deleteThread(threadId, opts = {}) {
2820
+ let url = "";
2821
+ if (opts.agentId) {
2822
+ url = `/api/memory/threads/${threadId}?agentId=${opts.agentId}`;
2823
+ } else if (opts.networkId) {
2824
+ url = `/api/memory/network/threads/${threadId}?networkId=${opts.networkId}`;
2825
+ }
2826
+ return this.request(url, { method: "DELETE" });
2827
+ }
1231
2828
  /**
1232
2829
  * Saves messages to memory
1233
2830
  * @param params - Parameters containing messages to save
@@ -1246,12 +2843,61 @@ var MastraClient = class extends BaseResource {
1246
2843
  getMemoryStatus(agentId) {
1247
2844
  return this.request(`/api/memory/status?agentId=${agentId}`);
1248
2845
  }
2846
+ /**
2847
+ * Retrieves memory threads for a resource
2848
+ * @param params - Parameters containing the resource ID
2849
+ * @returns Promise containing array of memory threads
2850
+ */
2851
+ getNetworkMemoryThreads(params) {
2852
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
2853
+ }
2854
+ /**
2855
+ * Creates a new memory thread
2856
+ * @param params - Parameters for creating the memory thread
2857
+ * @returns Promise containing the created memory thread
2858
+ */
2859
+ createNetworkMemoryThread(params) {
2860
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
2861
+ }
2862
+ /**
2863
+ * Gets a memory thread instance by ID
2864
+ * @param threadId - ID of the memory thread to retrieve
2865
+ * @returns MemoryThread instance
2866
+ */
2867
+ getNetworkMemoryThread(threadId, networkId) {
2868
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2869
+ }
2870
+ /**
2871
+ * Saves messages to memory
2872
+ * @param params - Parameters containing messages to save
2873
+ * @returns Promise containing the saved messages
2874
+ */
2875
+ saveNetworkMessageToMemory(params) {
2876
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2877
+ method: "POST",
2878
+ body: params
2879
+ });
2880
+ }
2881
+ /**
2882
+ * Gets the status of the memory system
2883
+ * @returns Promise containing memory system status
2884
+ */
2885
+ getNetworkMemoryStatus(networkId) {
2886
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2887
+ }
1249
2888
  /**
1250
2889
  * Retrieves all available tools
2890
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1251
2891
  * @returns Promise containing map of tool IDs to tool details
1252
2892
  */
1253
- getTools() {
1254
- return this.request("/api/tools");
2893
+ getTools(runtimeContext) {
2894
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2895
+ const searchParams = new URLSearchParams();
2896
+ if (runtimeContextParam) {
2897
+ searchParams.set("runtimeContext", runtimeContextParam);
2898
+ }
2899
+ const queryString = searchParams.toString();
2900
+ return this.request(`/api/tools${queryString ? `?${queryString}` : ""}`);
1255
2901
  }
1256
2902
  /**
1257
2903
  * Gets a tool instance by ID
@@ -1261,27 +2907,19 @@ var MastraClient = class extends BaseResource {
1261
2907
  getTool(toolId) {
1262
2908
  return new Tool(this.options, toolId);
1263
2909
  }
1264
- /**
1265
- * Retrieves all available legacy workflows
1266
- * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1267
- */
1268
- getLegacyWorkflows() {
1269
- return this.request("/api/workflows/legacy");
1270
- }
1271
- /**
1272
- * Gets a legacy workflow instance by ID
1273
- * @param workflowId - ID of the legacy workflow to retrieve
1274
- * @returns Legacy Workflow instance
1275
- */
1276
- getLegacyWorkflow(workflowId) {
1277
- return new LegacyWorkflow(this.options, workflowId);
1278
- }
1279
2910
  /**
1280
2911
  * Retrieves all available workflows
2912
+ * @param runtimeContext - Optional runtime context to pass as query parameter
1281
2913
  * @returns Promise containing map of workflow IDs to workflow details
1282
2914
  */
1283
- getWorkflows() {
1284
- return this.request("/api/workflows");
2915
+ getWorkflows(runtimeContext) {
2916
+ const runtimeContextParam = base64RuntimeContext(parseClientRuntimeContext(runtimeContext));
2917
+ const searchParams = new URLSearchParams();
2918
+ if (runtimeContextParam) {
2919
+ searchParams.set("runtimeContext", runtimeContextParam);
2920
+ }
2921
+ const queryString = searchParams.toString();
2922
+ return this.request(`/api/workflows${queryString ? `?${queryString}` : ""}`);
1285
2923
  }
1286
2924
  /**
1287
2925
  * Gets a workflow instance by ID
@@ -1291,6 +2929,20 @@ var MastraClient = class extends BaseResource {
1291
2929
  getWorkflow(workflowId) {
1292
2930
  return new Workflow(this.options, workflowId);
1293
2931
  }
2932
+ /**
2933
+ * Gets all available agent builder actions
2934
+ * @returns Promise containing map of action IDs to action details
2935
+ */
2936
+ getAgentBuilderActions() {
2937
+ return this.request("/api/agent-builder/");
2938
+ }
2939
+ /**
2940
+ * Gets an agent builder instance for executing agent-builder workflows
2941
+ * @returns AgentBuilder instance
2942
+ */
2943
+ getAgentBuilderAction(actionId) {
2944
+ return new AgentBuilder(this.options, actionId);
2945
+ }
1294
2946
  /**
1295
2947
  * Gets a vector instance by name
1296
2948
  * @param vectorName - Name of the vector to retrieve
@@ -1305,7 +2957,41 @@ var MastraClient = class extends BaseResource {
1305
2957
  * @returns Promise containing array of log messages
1306
2958
  */
1307
2959
  getLogs(params) {
1308
- return this.request(`/api/logs?transportId=${params.transportId}`);
2960
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2961
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2962
+ const searchParams = new URLSearchParams();
2963
+ if (transportId) {
2964
+ searchParams.set("transportId", transportId);
2965
+ }
2966
+ if (fromDate) {
2967
+ searchParams.set("fromDate", fromDate.toISOString());
2968
+ }
2969
+ if (toDate) {
2970
+ searchParams.set("toDate", toDate.toISOString());
2971
+ }
2972
+ if (logLevel) {
2973
+ searchParams.set("logLevel", logLevel);
2974
+ }
2975
+ if (page) {
2976
+ searchParams.set("page", String(page));
2977
+ }
2978
+ if (perPage) {
2979
+ searchParams.set("perPage", String(perPage));
2980
+ }
2981
+ if (_filters) {
2982
+ if (Array.isArray(_filters)) {
2983
+ for (const filter of _filters) {
2984
+ searchParams.append("filters", filter);
2985
+ }
2986
+ } else {
2987
+ searchParams.set("filters", _filters);
2988
+ }
2989
+ }
2990
+ if (searchParams.size) {
2991
+ return this.request(`/api/logs?${searchParams}`);
2992
+ } else {
2993
+ return this.request(`/api/logs`);
2994
+ }
1309
2995
  }
1310
2996
  /**
1311
2997
  * Gets logs for a specific run
@@ -1313,7 +2999,44 @@ var MastraClient = class extends BaseResource {
1313
2999
  * @returns Promise containing array of log messages
1314
3000
  */
1315
3001
  getLogForRun(params) {
1316
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
3002
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
3003
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
3004
+ const searchParams = new URLSearchParams();
3005
+ if (runId) {
3006
+ searchParams.set("runId", runId);
3007
+ }
3008
+ if (transportId) {
3009
+ searchParams.set("transportId", transportId);
3010
+ }
3011
+ if (fromDate) {
3012
+ searchParams.set("fromDate", fromDate.toISOString());
3013
+ }
3014
+ if (toDate) {
3015
+ searchParams.set("toDate", toDate.toISOString());
3016
+ }
3017
+ if (logLevel) {
3018
+ searchParams.set("logLevel", logLevel);
3019
+ }
3020
+ if (page) {
3021
+ searchParams.set("page", String(page));
3022
+ }
3023
+ if (perPage) {
3024
+ searchParams.set("perPage", String(perPage));
3025
+ }
3026
+ if (_filters) {
3027
+ if (Array.isArray(_filters)) {
3028
+ for (const filter of _filters) {
3029
+ searchParams.append("filters", filter);
3030
+ }
3031
+ } else {
3032
+ searchParams.set("filters", _filters);
3033
+ }
3034
+ }
3035
+ if (searchParams.size) {
3036
+ return this.request(`/api/logs/${runId}?${searchParams}`);
3037
+ } else {
3038
+ return this.request(`/api/logs/${runId}`);
3039
+ }
1317
3040
  }
1318
3041
  /**
1319
3042
  * List of all log transports
@@ -1365,19 +3088,19 @@ var MastraClient = class extends BaseResource {
1365
3088
  }
1366
3089
  }
1367
3090
  /**
1368
- * Retrieves all available networks
1369
- * @returns Promise containing map of network IDs to network details
3091
+ * Retrieves all available vNext networks
3092
+ * @returns Promise containing map of vNext network IDs to vNext network details
1370
3093
  */
1371
- getNetworks() {
1372
- return this.request("/api/networks");
3094
+ getVNextNetworks() {
3095
+ return this.request("/api/networks/v-next");
1373
3096
  }
1374
3097
  /**
1375
- * Gets a network instance by ID
1376
- * @param networkId - ID of the network to retrieve
1377
- * @returns Network instance
3098
+ * Gets a vNext network instance by ID
3099
+ * @param networkId - ID of the vNext network to retrieve
3100
+ * @returns vNext Network instance
1378
3101
  */
1379
- getNetwork(networkId) {
1380
- return new Network(this.options, networkId);
3102
+ getVNextNetwork(networkId) {
3103
+ return new VNextNetwork(this.options, networkId);
1381
3104
  }
1382
3105
  /**
1383
3106
  * Retrieves a list of available MCP servers.
@@ -1435,6 +3158,158 @@ var MastraClient = class extends BaseResource {
1435
3158
  getA2A(agentId) {
1436
3159
  return new A2A(this.options, agentId);
1437
3160
  }
3161
+ /**
3162
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
3163
+ * @param agentId - ID of the agent.
3164
+ * @param threadId - ID of the thread.
3165
+ * @param resourceId - Optional ID of the resource.
3166
+ * @returns Working memory for the specified thread or resource.
3167
+ */
3168
+ getWorkingMemory({
3169
+ agentId,
3170
+ threadId,
3171
+ resourceId
3172
+ }) {
3173
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
3174
+ }
3175
+ /**
3176
+ * Updates the working memory for a specific thread (optionally resource-scoped).
3177
+ * @param agentId - ID of the agent.
3178
+ * @param threadId - ID of the thread.
3179
+ * @param workingMemory - The new working memory content.
3180
+ * @param resourceId - Optional ID of the resource.
3181
+ */
3182
+ updateWorkingMemory({
3183
+ agentId,
3184
+ threadId,
3185
+ workingMemory,
3186
+ resourceId
3187
+ }) {
3188
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
3189
+ method: "POST",
3190
+ body: {
3191
+ workingMemory,
3192
+ resourceId
3193
+ }
3194
+ });
3195
+ }
3196
+ /**
3197
+ * Retrieves all available scorers
3198
+ * @returns Promise containing list of available scorers
3199
+ */
3200
+ getScorers() {
3201
+ return this.request("/api/scores/scorers");
3202
+ }
3203
+ /**
3204
+ * Retrieves a scorer by ID
3205
+ * @param scorerId - ID of the scorer to retrieve
3206
+ * @returns Promise containing the scorer
3207
+ */
3208
+ getScorer(scorerId) {
3209
+ return this.request(`/api/scores/scorers/${scorerId}`);
3210
+ }
3211
+ getScoresByScorerId(params) {
3212
+ const { page, perPage, scorerId, entityId, entityType } = params;
3213
+ const searchParams = new URLSearchParams();
3214
+ if (entityId) {
3215
+ searchParams.set("entityId", entityId);
3216
+ }
3217
+ if (entityType) {
3218
+ searchParams.set("entityType", entityType);
3219
+ }
3220
+ if (page !== void 0) {
3221
+ searchParams.set("page", String(page));
3222
+ }
3223
+ if (perPage !== void 0) {
3224
+ searchParams.set("perPage", String(perPage));
3225
+ }
3226
+ const queryString = searchParams.toString();
3227
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
3228
+ }
3229
+ /**
3230
+ * Retrieves scores by run ID
3231
+ * @param params - Parameters containing run ID and pagination options
3232
+ * @returns Promise containing scores and pagination info
3233
+ */
3234
+ getScoresByRunId(params) {
3235
+ const { runId, page, perPage } = params;
3236
+ const searchParams = new URLSearchParams();
3237
+ if (page !== void 0) {
3238
+ searchParams.set("page", String(page));
3239
+ }
3240
+ if (perPage !== void 0) {
3241
+ searchParams.set("perPage", String(perPage));
3242
+ }
3243
+ const queryString = searchParams.toString();
3244
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
3245
+ }
3246
+ /**
3247
+ * Retrieves scores by entity ID and type
3248
+ * @param params - Parameters containing entity ID, type, and pagination options
3249
+ * @returns Promise containing scores and pagination info
3250
+ */
3251
+ getScoresByEntityId(params) {
3252
+ const { entityId, entityType, page, perPage } = params;
3253
+ const searchParams = new URLSearchParams();
3254
+ if (page !== void 0) {
3255
+ searchParams.set("page", String(page));
3256
+ }
3257
+ if (perPage !== void 0) {
3258
+ searchParams.set("perPage", String(perPage));
3259
+ }
3260
+ const queryString = searchParams.toString();
3261
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
3262
+ }
3263
+ /**
3264
+ * Saves a score
3265
+ * @param params - Parameters containing the score data to save
3266
+ * @returns Promise containing the saved score
3267
+ */
3268
+ saveScore(params) {
3269
+ return this.request("/api/scores", {
3270
+ method: "POST",
3271
+ body: params
3272
+ });
3273
+ }
3274
+ /**
3275
+ * Retrieves model providers with available keys
3276
+ * @returns Promise containing model providers with available keys
3277
+ */
3278
+ getModelProviders() {
3279
+ return this.request(`/api/model-providers`);
3280
+ }
3281
+ getAITrace(traceId) {
3282
+ return this.observability.getTrace(traceId);
3283
+ }
3284
+ getAITraces(params) {
3285
+ return this.observability.getTraces(params);
3286
+ }
3287
+ score(params) {
3288
+ return this.observability.score(params);
3289
+ }
1438
3290
  };
1439
3291
 
3292
+ // src/tools.ts
3293
+ var ClientTool = class {
3294
+ id;
3295
+ description;
3296
+ inputSchema;
3297
+ outputSchema;
3298
+ execute;
3299
+ constructor(opts) {
3300
+ this.id = opts.id;
3301
+ this.description = opts.description;
3302
+ this.inputSchema = opts.inputSchema;
3303
+ this.outputSchema = opts.outputSchema;
3304
+ this.execute = opts.execute;
3305
+ }
3306
+ };
3307
+ function createTool(opts) {
3308
+ return new ClientTool(opts);
3309
+ }
3310
+
3311
+ exports.ClientTool = ClientTool;
1440
3312
  exports.MastraClient = MastraClient;
3313
+ exports.createTool = createTool;
3314
+ //# sourceMappingURL=index.cjs.map
3315
+ //# sourceMappingURL=index.cjs.map