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