@mastra/client-js 0.0.0-cloud-transporter-20250513033346 → 0.0.0-cloud-storage-adapter-20251106204059

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