@mastra/client-js 0.0.0-commonjs-20250227130920 → 0.0.0-consolidate-changesets-20250904042643

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