@mastra/client-js 0.0.0-message-list-update-20250715150321 → 0.0.0-monorepo-binary-20251013210052

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