@mastra/client-js 0.0.0-cli-debug-2-20250611100354 → 0.0.0-cloud-deployer-for-core-0.19.1-20251001164939

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