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

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