@mastra/client-js 0.0.0-generate-message-id-20250512171942 → 0.0.0-gl-test-20250917080133

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