@mastra/client-js 0.0.0-vector-sources-20250516175436 → 0.0.0-vector-extension-schema-20250922130418

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