@mastra/client-js 0.0.0-message-ordering-20250415215612 → 0.0.0-message-list-update-20250715150321

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.
package/dist/index.js CHANGED
@@ -1,8 +1,230 @@
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
+ import { processTextStream, processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
1
4
  import { ZodSchema } from 'zod';
2
- import { zodToJsonSchema } from 'zod-to-json-schema';
3
- import { processDataStream } from '@ai-sdk/ui-utils';
5
+ import originalZodToJsonSchema from 'zod-to-json-schema';
6
+ import { isVercelTool } from '@mastra/core/tools';
7
+ import { v4 } from '@lukeed/uuid';
8
+ import { RuntimeContext } from '@mastra/core/runtime-context';
4
9
 
5
- // src/resources/agent.ts
10
+ // src/adapters/agui.ts
11
+ var AGUIAdapter = class extends AbstractAgent {
12
+ agent;
13
+ resourceId;
14
+ constructor({ agent, agentId, resourceId, ...rest }) {
15
+ super({
16
+ agentId,
17
+ ...rest
18
+ });
19
+ this.agent = agent;
20
+ this.resourceId = resourceId;
21
+ }
22
+ run(input) {
23
+ return new Observable((subscriber) => {
24
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
25
+ subscriber.next({
26
+ type: EventType.RUN_STARTED,
27
+ threadId: input.threadId,
28
+ runId: input.runId
29
+ });
30
+ this.agent.stream({
31
+ threadId: input.threadId,
32
+ resourceId: this.resourceId ?? "",
33
+ runId: input.runId,
34
+ messages: convertedMessages,
35
+ clientTools: input.tools.reduce(
36
+ (acc, tool) => {
37
+ acc[tool.name] = {
38
+ id: tool.name,
39
+ description: tool.description,
40
+ inputSchema: tool.parameters
41
+ };
42
+ return acc;
43
+ },
44
+ {}
45
+ )
46
+ }).then((response) => {
47
+ let currentMessageId = void 0;
48
+ let isInTextMessage = false;
49
+ return response.processDataStream({
50
+ onTextPart: (text) => {
51
+ if (currentMessageId === void 0) {
52
+ currentMessageId = generateUUID();
53
+ const message2 = {
54
+ type: EventType.TEXT_MESSAGE_START,
55
+ messageId: currentMessageId,
56
+ role: "assistant"
57
+ };
58
+ subscriber.next(message2);
59
+ isInTextMessage = true;
60
+ }
61
+ const message = {
62
+ type: EventType.TEXT_MESSAGE_CONTENT,
63
+ messageId: currentMessageId,
64
+ delta: text
65
+ };
66
+ subscriber.next(message);
67
+ },
68
+ onFinishMessagePart: () => {
69
+ if (currentMessageId !== void 0) {
70
+ const message = {
71
+ type: EventType.TEXT_MESSAGE_END,
72
+ messageId: currentMessageId
73
+ };
74
+ subscriber.next(message);
75
+ isInTextMessage = false;
76
+ }
77
+ subscriber.next({
78
+ type: EventType.RUN_FINISHED,
79
+ threadId: input.threadId,
80
+ runId: input.runId
81
+ });
82
+ subscriber.complete();
83
+ },
84
+ onToolCallPart(streamPart) {
85
+ const parentMessageId = currentMessageId || generateUUID();
86
+ if (isInTextMessage) {
87
+ const message = {
88
+ type: EventType.TEXT_MESSAGE_END,
89
+ messageId: parentMessageId
90
+ };
91
+ subscriber.next(message);
92
+ isInTextMessage = false;
93
+ }
94
+ subscriber.next({
95
+ type: EventType.TOOL_CALL_START,
96
+ toolCallId: streamPart.toolCallId,
97
+ toolCallName: streamPart.toolName,
98
+ parentMessageId
99
+ });
100
+ subscriber.next({
101
+ type: EventType.TOOL_CALL_ARGS,
102
+ toolCallId: streamPart.toolCallId,
103
+ delta: JSON.stringify(streamPart.args),
104
+ parentMessageId
105
+ });
106
+ subscriber.next({
107
+ type: EventType.TOOL_CALL_END,
108
+ toolCallId: streamPart.toolCallId,
109
+ parentMessageId
110
+ });
111
+ }
112
+ });
113
+ }).catch((error) => {
114
+ console.error("error", error);
115
+ subscriber.error(error);
116
+ });
117
+ return () => {
118
+ };
119
+ });
120
+ }
121
+ };
122
+ function generateUUID() {
123
+ if (typeof crypto !== "undefined") {
124
+ if (typeof crypto.randomUUID === "function") {
125
+ return crypto.randomUUID();
126
+ }
127
+ if (typeof crypto.getRandomValues === "function") {
128
+ const buffer = new Uint8Array(16);
129
+ crypto.getRandomValues(buffer);
130
+ buffer[6] = buffer[6] & 15 | 64;
131
+ buffer[8] = buffer[8] & 63 | 128;
132
+ let hex = "";
133
+ for (let i = 0; i < 16; i++) {
134
+ hex += buffer[i].toString(16).padStart(2, "0");
135
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
136
+ }
137
+ return hex;
138
+ }
139
+ }
140
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
141
+ const r = Math.random() * 16 | 0;
142
+ const v = c === "x" ? r : r & 3 | 8;
143
+ return v.toString(16);
144
+ });
145
+ }
146
+ function convertMessagesToMastraMessages(messages) {
147
+ const result = [];
148
+ for (const message of messages) {
149
+ if (message.role === "assistant") {
150
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
151
+ for (const toolCall of message.toolCalls ?? []) {
152
+ parts.push({
153
+ type: "tool-call",
154
+ toolCallId: toolCall.id,
155
+ toolName: toolCall.function.name,
156
+ args: JSON.parse(toolCall.function.arguments)
157
+ });
158
+ }
159
+ result.push({
160
+ role: "assistant",
161
+ content: parts
162
+ });
163
+ if (message.toolCalls?.length) {
164
+ result.push({
165
+ role: "tool",
166
+ content: message.toolCalls.map((toolCall) => ({
167
+ type: "tool-result",
168
+ toolCallId: toolCall.id,
169
+ toolName: toolCall.function.name,
170
+ result: JSON.parse(toolCall.function.arguments)
171
+ }))
172
+ });
173
+ }
174
+ } else if (message.role === "user") {
175
+ result.push({
176
+ role: "user",
177
+ content: message.content || ""
178
+ });
179
+ } else if (message.role === "tool") {
180
+ result.push({
181
+ role: "tool",
182
+ content: [
183
+ {
184
+ type: "tool-result",
185
+ toolCallId: message.toolCallId,
186
+ toolName: "unknown",
187
+ result: message.content
188
+ }
189
+ ]
190
+ });
191
+ }
192
+ }
193
+ return result;
194
+ }
195
+ function zodToJsonSchema(zodSchema) {
196
+ if (!(zodSchema instanceof ZodSchema)) {
197
+ return zodSchema;
198
+ }
199
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
200
+ }
201
+ function processClientTools(clientTools) {
202
+ if (!clientTools) {
203
+ return void 0;
204
+ }
205
+ return Object.fromEntries(
206
+ Object.entries(clientTools).map(([key, value]) => {
207
+ if (isVercelTool(value)) {
208
+ return [
209
+ key,
210
+ {
211
+ ...value,
212
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
213
+ }
214
+ ];
215
+ } else {
216
+ return [
217
+ key,
218
+ {
219
+ ...value,
220
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
221
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
222
+ }
223
+ ];
224
+ }
225
+ })
226
+ );
227
+ }
6
228
 
7
229
  // src/resources/base.ts
8
230
  var BaseResource = class {
@@ -22,14 +244,16 @@ var BaseResource = class {
22
244
  let delay = backoffMs;
23
245
  for (let attempt = 0; attempt <= retries; attempt++) {
24
246
  try {
25
- const response = await fetch(`${baseUrl}${path}`, {
247
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
26
248
  ...options,
27
249
  headers: {
250
+ ...options.method === "POST" || options.method === "PUT" ? { "content-type": "application/json" } : {},
28
251
  ...headers,
29
252
  ...options.headers
30
253
  // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
31
254
  // 'x-mastra-client-type': 'js',
32
255
  },
256
+ signal: this.options.abortSignal,
33
257
  body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
34
258
  });
35
259
  if (!response.ok) {
@@ -62,8 +286,15 @@ var BaseResource = class {
62
286
  throw lastError || new Error("Request failed");
63
287
  }
64
288
  };
65
-
66
- // src/resources/agent.ts
289
+ function parseClientRuntimeContext(runtimeContext) {
290
+ if (runtimeContext) {
291
+ if (runtimeContext instanceof RuntimeContext) {
292
+ return Object.fromEntries(runtimeContext.entries());
293
+ }
294
+ return runtimeContext;
295
+ }
296
+ return void 0;
297
+ }
67
298
  var AgentVoice = class extends BaseResource {
68
299
  constructor(options, agentId) {
69
300
  super(options);
@@ -110,6 +341,13 @@ var AgentVoice = class extends BaseResource {
110
341
  getSpeakers() {
111
342
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
112
343
  }
344
+ /**
345
+ * Get the listener configuration for the agent's voice provider
346
+ * @returns Promise containing a check if the agent has listening capabilities
347
+ */
348
+ getListener() {
349
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
350
+ }
113
351
  };
114
352
  var Agent = class extends BaseResource {
115
353
  constructor(options, agentId) {
@@ -125,33 +363,341 @@ var Agent = class extends BaseResource {
125
363
  details() {
126
364
  return this.request(`/api/agents/${this.agentId}`);
127
365
  }
128
- /**
129
- * Generates a response from the agent
130
- * @param params - Generation parameters including prompt
131
- * @returns Promise containing the generated response
132
- */
133
- generate(params) {
366
+ async generate(params) {
134
367
  const processedParams = {
135
368
  ...params,
136
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
137
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
369
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
370
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
371
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
372
+ clientTools: processClientTools(params.clientTools)
138
373
  };
139
- return this.request(`/api/agents/${this.agentId}/generate`, {
374
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
375
+ const response = await this.request(`/api/agents/${this.agentId}/generate`, {
140
376
  method: "POST",
141
377
  body: processedParams
142
378
  });
379
+ if (response.finishReason === "tool-calls") {
380
+ const toolCalls = response.toolCalls;
381
+ if (!toolCalls || !Array.isArray(toolCalls)) {
382
+ return response;
383
+ }
384
+ for (const toolCall of toolCalls) {
385
+ const clientTool = params.clientTools?.[toolCall.toolName];
386
+ if (clientTool && clientTool.execute) {
387
+ const result = await clientTool.execute(
388
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
389
+ {
390
+ messages: response.messages,
391
+ toolCallId: toolCall?.toolCallId
392
+ }
393
+ );
394
+ const updatedMessages = [
395
+ {
396
+ role: "user",
397
+ content: params.messages
398
+ },
399
+ ...response.response.messages,
400
+ {
401
+ role: "tool",
402
+ content: [
403
+ {
404
+ type: "tool-result",
405
+ toolCallId: toolCall.toolCallId,
406
+ toolName: toolCall.toolName,
407
+ result
408
+ }
409
+ ]
410
+ }
411
+ ];
412
+ return this.generate({
413
+ ...params,
414
+ messages: updatedMessages
415
+ });
416
+ }
417
+ }
418
+ }
419
+ return response;
420
+ }
421
+ async processChatResponse({
422
+ stream,
423
+ update,
424
+ onToolCall,
425
+ onFinish,
426
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
427
+ lastMessage,
428
+ streamProtocol
429
+ }) {
430
+ const replaceLastMessage = lastMessage?.role === "assistant";
431
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
432
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
433
+ return Math.max(max, toolInvocation.step ?? 0);
434
+ }, 0) ?? 0) : 0;
435
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
436
+ id: v4(),
437
+ createdAt: getCurrentDate(),
438
+ role: "assistant",
439
+ content: "",
440
+ parts: []
441
+ };
442
+ let currentTextPart = void 0;
443
+ let currentReasoningPart = void 0;
444
+ let currentReasoningTextDetail = void 0;
445
+ function updateToolInvocationPart(toolCallId, invocation) {
446
+ const part = message.parts.find(
447
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
448
+ );
449
+ if (part != null) {
450
+ part.toolInvocation = invocation;
451
+ } else {
452
+ message.parts.push({
453
+ type: "tool-invocation",
454
+ toolInvocation: invocation
455
+ });
456
+ }
457
+ }
458
+ const data = [];
459
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
460
+ const partialToolCalls = {};
461
+ let usage = {
462
+ completionTokens: NaN,
463
+ promptTokens: NaN,
464
+ totalTokens: NaN
465
+ };
466
+ let finishReason = "unknown";
467
+ function execUpdate() {
468
+ const copiedData = [...data];
469
+ if (messageAnnotations?.length) {
470
+ message.annotations = messageAnnotations;
471
+ }
472
+ const copiedMessage = {
473
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
474
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
475
+ ...structuredClone(message),
476
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
477
+ // hashing approach by default to detect changes, but it only works for shallow
478
+ // changes. This is why we need to add a revision id to ensure that the message
479
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
480
+ // forwarded to rendering):
481
+ revisionId: v4()
482
+ };
483
+ update({
484
+ message: copiedMessage,
485
+ data: copiedData,
486
+ replaceLastMessage
487
+ });
488
+ }
489
+ if (streamProtocol === "text") {
490
+ await processTextStream({
491
+ stream,
492
+ onTextPart(value) {
493
+ message.content += value;
494
+ execUpdate();
495
+ }
496
+ });
497
+ onFinish?.({ message, finishReason, usage });
498
+ } else {
499
+ await processDataStream({
500
+ stream,
501
+ onTextPart(value) {
502
+ if (currentTextPart == null) {
503
+ currentTextPart = {
504
+ type: "text",
505
+ text: value
506
+ };
507
+ message.parts.push(currentTextPart);
508
+ } else {
509
+ currentTextPart.text += value;
510
+ }
511
+ message.content += value;
512
+ execUpdate();
513
+ },
514
+ onReasoningPart(value) {
515
+ if (currentReasoningTextDetail == null) {
516
+ currentReasoningTextDetail = { type: "text", text: value };
517
+ if (currentReasoningPart != null) {
518
+ currentReasoningPart.details.push(currentReasoningTextDetail);
519
+ }
520
+ } else {
521
+ currentReasoningTextDetail.text += value;
522
+ }
523
+ if (currentReasoningPart == null) {
524
+ currentReasoningPart = {
525
+ type: "reasoning",
526
+ reasoning: value,
527
+ details: [currentReasoningTextDetail]
528
+ };
529
+ message.parts.push(currentReasoningPart);
530
+ } else {
531
+ currentReasoningPart.reasoning += value;
532
+ }
533
+ message.reasoning = (message.reasoning ?? "") + value;
534
+ execUpdate();
535
+ },
536
+ onReasoningSignaturePart(value) {
537
+ if (currentReasoningTextDetail != null) {
538
+ currentReasoningTextDetail.signature = value.signature;
539
+ }
540
+ },
541
+ onRedactedReasoningPart(value) {
542
+ if (currentReasoningPart == null) {
543
+ currentReasoningPart = {
544
+ type: "reasoning",
545
+ reasoning: "",
546
+ details: []
547
+ };
548
+ message.parts.push(currentReasoningPart);
549
+ }
550
+ currentReasoningPart.details.push({
551
+ type: "redacted",
552
+ data: value.data
553
+ });
554
+ currentReasoningTextDetail = void 0;
555
+ execUpdate();
556
+ },
557
+ onFilePart(value) {
558
+ message.parts.push({
559
+ type: "file",
560
+ mimeType: value.mimeType,
561
+ data: value.data
562
+ });
563
+ execUpdate();
564
+ },
565
+ onSourcePart(value) {
566
+ message.parts.push({
567
+ type: "source",
568
+ source: value
569
+ });
570
+ execUpdate();
571
+ },
572
+ onToolCallStreamingStartPart(value) {
573
+ if (message.toolInvocations == null) {
574
+ message.toolInvocations = [];
575
+ }
576
+ partialToolCalls[value.toolCallId] = {
577
+ text: "",
578
+ step,
579
+ toolName: value.toolName,
580
+ index: message.toolInvocations.length
581
+ };
582
+ const invocation = {
583
+ state: "partial-call",
584
+ step,
585
+ toolCallId: value.toolCallId,
586
+ toolName: value.toolName,
587
+ args: void 0
588
+ };
589
+ message.toolInvocations.push(invocation);
590
+ updateToolInvocationPart(value.toolCallId, invocation);
591
+ execUpdate();
592
+ },
593
+ onToolCallDeltaPart(value) {
594
+ const partialToolCall = partialToolCalls[value.toolCallId];
595
+ partialToolCall.text += value.argsTextDelta;
596
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
597
+ const invocation = {
598
+ state: "partial-call",
599
+ step: partialToolCall.step,
600
+ toolCallId: value.toolCallId,
601
+ toolName: partialToolCall.toolName,
602
+ args: partialArgs
603
+ };
604
+ message.toolInvocations[partialToolCall.index] = invocation;
605
+ updateToolInvocationPart(value.toolCallId, invocation);
606
+ execUpdate();
607
+ },
608
+ async onToolCallPart(value) {
609
+ const invocation = {
610
+ state: "call",
611
+ step,
612
+ ...value
613
+ };
614
+ if (partialToolCalls[value.toolCallId] != null) {
615
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
616
+ } else {
617
+ if (message.toolInvocations == null) {
618
+ message.toolInvocations = [];
619
+ }
620
+ message.toolInvocations.push(invocation);
621
+ }
622
+ updateToolInvocationPart(value.toolCallId, invocation);
623
+ execUpdate();
624
+ if (onToolCall) {
625
+ const result = await onToolCall({ toolCall: value });
626
+ if (result != null) {
627
+ const invocation2 = {
628
+ state: "result",
629
+ step,
630
+ ...value,
631
+ result
632
+ };
633
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
634
+ updateToolInvocationPart(value.toolCallId, invocation2);
635
+ execUpdate();
636
+ }
637
+ }
638
+ },
639
+ onToolResultPart(value) {
640
+ const toolInvocations = message.toolInvocations;
641
+ if (toolInvocations == null) {
642
+ throw new Error("tool_result must be preceded by a tool_call");
643
+ }
644
+ const toolInvocationIndex = toolInvocations.findIndex(
645
+ (invocation2) => invocation2.toolCallId === value.toolCallId
646
+ );
647
+ if (toolInvocationIndex === -1) {
648
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
649
+ }
650
+ const invocation = {
651
+ ...toolInvocations[toolInvocationIndex],
652
+ state: "result",
653
+ ...value
654
+ };
655
+ toolInvocations[toolInvocationIndex] = invocation;
656
+ updateToolInvocationPart(value.toolCallId, invocation);
657
+ execUpdate();
658
+ },
659
+ onDataPart(value) {
660
+ data.push(...value);
661
+ execUpdate();
662
+ },
663
+ onMessageAnnotationsPart(value) {
664
+ if (messageAnnotations == null) {
665
+ messageAnnotations = [...value];
666
+ } else {
667
+ messageAnnotations.push(...value);
668
+ }
669
+ execUpdate();
670
+ },
671
+ onFinishStepPart(value) {
672
+ step += 1;
673
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
674
+ currentReasoningPart = void 0;
675
+ currentReasoningTextDetail = void 0;
676
+ },
677
+ onStartStepPart(value) {
678
+ if (!replaceLastMessage) {
679
+ message.id = value.messageId;
680
+ }
681
+ message.parts.push({ type: "step-start" });
682
+ execUpdate();
683
+ },
684
+ onFinishMessagePart(value) {
685
+ finishReason = value.finishReason;
686
+ if (value.usage != null) {
687
+ usage = value.usage;
688
+ }
689
+ },
690
+ onErrorPart(error) {
691
+ throw new Error(error);
692
+ }
693
+ });
694
+ onFinish?.({ message, finishReason, usage });
695
+ }
143
696
  }
144
697
  /**
145
- * Streams a response from the agent
146
- * @param params - Stream parameters including prompt
147
- * @returns Promise containing the enhanced Response object with processDataStream method
698
+ * Processes the stream response and handles tool calls
148
699
  */
149
- async stream(params) {
150
- const processedParams = {
151
- ...params,
152
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
153
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
154
- };
700
+ async processStreamResponse(processedParams, writable) {
155
701
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
156
702
  method: "POST",
157
703
  body: processedParams,
@@ -160,13 +706,135 @@ var Agent = class extends BaseResource {
160
706
  if (!response.body) {
161
707
  throw new Error("No response body");
162
708
  }
163
- response.processDataStream = async (options = {}) => {
709
+ try {
710
+ const streamProtocol = processedParams.output ? "text" : "data";
711
+ let toolCalls = [];
712
+ let messages = [];
713
+ const [streamForWritable, streamForProcessing] = response.body.tee();
714
+ streamForWritable.pipeTo(writable, {
715
+ preventClose: true
716
+ }).catch((error) => {
717
+ console.error("Error piping to writable stream:", error);
718
+ });
719
+ this.processChatResponse({
720
+ stream: streamForProcessing,
721
+ update: ({ message }) => {
722
+ messages.push(message);
723
+ },
724
+ onFinish: async ({ finishReason, message }) => {
725
+ if (finishReason === "tool-calls") {
726
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
727
+ if (toolCall) {
728
+ toolCalls.push(toolCall);
729
+ }
730
+ for (const toolCall2 of toolCalls) {
731
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
732
+ if (clientTool && clientTool.execute) {
733
+ const result = await clientTool.execute(
734
+ {
735
+ context: toolCall2?.args,
736
+ runId: processedParams.runId,
737
+ resourceId: processedParams.resourceId,
738
+ threadId: processedParams.threadId,
739
+ runtimeContext: processedParams.runtimeContext
740
+ },
741
+ {
742
+ messages: response.messages,
743
+ toolCallId: toolCall2?.toolCallId
744
+ }
745
+ );
746
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
747
+ const toolInvocationPart = lastMessage?.parts?.find(
748
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
749
+ );
750
+ if (toolInvocationPart) {
751
+ toolInvocationPart.toolInvocation = {
752
+ ...toolInvocationPart.toolInvocation,
753
+ state: "result",
754
+ result
755
+ };
756
+ }
757
+ const toolInvocation = lastMessage?.toolInvocations?.find(
758
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
759
+ );
760
+ if (toolInvocation) {
761
+ toolInvocation.state = "result";
762
+ toolInvocation.result = result;
763
+ }
764
+ const writer = writable.getWriter();
765
+ try {
766
+ await writer.write(
767
+ new TextEncoder().encode(
768
+ "a:" + JSON.stringify({
769
+ toolCallId: toolCall2.toolCallId,
770
+ result
771
+ }) + "\n"
772
+ )
773
+ );
774
+ } finally {
775
+ writer.releaseLock();
776
+ }
777
+ const originalMessages = processedParams.messages;
778
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
779
+ this.processStreamResponse(
780
+ {
781
+ ...processedParams,
782
+ messages: [...messageArray, ...messages, lastMessage]
783
+ },
784
+ writable
785
+ );
786
+ }
787
+ }
788
+ } else {
789
+ setTimeout(() => {
790
+ if (!writable.locked) {
791
+ writable.close();
792
+ }
793
+ }, 0);
794
+ }
795
+ },
796
+ lastMessage: void 0,
797
+ streamProtocol
798
+ });
799
+ } catch (error) {
800
+ console.error("Error processing stream response:", error);
801
+ }
802
+ return response;
803
+ }
804
+ /**
805
+ * Streams a response from the agent
806
+ * @param params - Stream parameters including prompt
807
+ * @returns Promise containing the enhanced Response object with processDataStream and processTextStream methods
808
+ */
809
+ async stream(params) {
810
+ const processedParams = {
811
+ ...params,
812
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
813
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
814
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
815
+ clientTools: processClientTools(params.clientTools)
816
+ };
817
+ const { readable, writable } = new TransformStream();
818
+ const response = await this.processStreamResponse(processedParams, writable);
819
+ const streamResponse = new Response(readable, {
820
+ status: response.status,
821
+ statusText: response.statusText,
822
+ headers: response.headers
823
+ });
824
+ streamResponse.processDataStream = async (options = {}) => {
164
825
  await processDataStream({
165
- stream: response.body,
826
+ stream: streamResponse.body,
166
827
  ...options
167
828
  });
168
829
  };
169
- return response;
830
+ streamResponse.processTextStream = async (options) => {
831
+ await processTextStream({
832
+ stream: streamResponse.body,
833
+ onTextPart: options?.onTextPart ?? (() => {
834
+ })
835
+ });
836
+ };
837
+ return streamResponse;
170
838
  }
171
839
  /**
172
840
  * Gets details about a specific tool available to the agent
@@ -176,6 +844,22 @@ var Agent = class extends BaseResource {
176
844
  getTool(toolId) {
177
845
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
178
846
  }
847
+ /**
848
+ * Executes a tool for the agent
849
+ * @param toolId - ID of the tool to execute
850
+ * @param params - Parameters required for tool execution
851
+ * @returns Promise containing the tool execution results
852
+ */
853
+ executeTool(toolId, params) {
854
+ const body = {
855
+ data: params.data,
856
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
857
+ };
858
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
859
+ method: "POST",
860
+ body
861
+ });
862
+ }
179
863
  /**
180
864
  * Retrieves evaluation results for the agent
181
865
  * @returns Promise containing agent evaluations
@@ -211,8 +895,8 @@ var Network = class extends BaseResource {
211
895
  generate(params) {
212
896
  const processedParams = {
213
897
  ...params,
214
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
215
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
898
+ output: zodToJsonSchema(params.output),
899
+ experimental_output: zodToJsonSchema(params.experimental_output)
216
900
  };
217
901
  return this.request(`/api/networks/${this.networkId}/generate`, {
218
902
  method: "POST",
@@ -227,8 +911,8 @@ var Network = class extends BaseResource {
227
911
  async stream(params) {
228
912
  const processedParams = {
229
913
  ...params,
230
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
231
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
914
+ output: zodToJsonSchema(params.output),
915
+ experimental_output: zodToJsonSchema(params.experimental_output)
232
916
  };
233
917
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
234
918
  method: "POST",
@@ -284,10 +968,15 @@ var MemoryThread = class extends BaseResource {
284
968
  }
285
969
  /**
286
970
  * Retrieves messages associated with the thread
971
+ * @param params - Optional parameters including limit for number of messages to retrieve
287
972
  * @returns Promise containing thread messages and UI messages
288
973
  */
289
- getMessages() {
290
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
974
+ getMessages(params) {
975
+ const query = new URLSearchParams({
976
+ agentId: this.agentId,
977
+ ...params?.limit ? { limit: params.limit.toString() } : {}
978
+ });
979
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
291
980
  }
292
981
  };
293
982
 
@@ -357,34 +1046,50 @@ var Vector = class extends BaseResource {
357
1046
  }
358
1047
  };
359
1048
 
360
- // src/resources/workflow.ts
1049
+ // src/resources/legacy-workflow.ts
361
1050
  var RECORD_SEPARATOR = "";
362
- var Workflow = class extends BaseResource {
1051
+ var LegacyWorkflow = class extends BaseResource {
363
1052
  constructor(options, workflowId) {
364
1053
  super(options);
365
1054
  this.workflowId = workflowId;
366
1055
  }
367
1056
  /**
368
- * Retrieves details about the workflow
369
- * @returns Promise containing workflow details including steps and graphs
1057
+ * Retrieves details about the legacy workflow
1058
+ * @returns Promise containing legacy workflow details including steps and graphs
370
1059
  */
371
1060
  details() {
372
- return this.request(`/api/workflows/${this.workflowId}`);
1061
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
373
1062
  }
374
1063
  /**
375
- * @deprecated Use `startAsync` instead
376
- * Executes the workflow with the provided parameters
377
- * @param params - Parameters required for workflow execution
378
- * @returns Promise containing the workflow execution results
1064
+ * Retrieves all runs for a legacy workflow
1065
+ * @param params - Parameters for filtering runs
1066
+ * @returns Promise containing legacy workflow runs array
379
1067
  */
380
- execute(params) {
381
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
382
- method: "POST",
383
- body: params
384
- });
1068
+ runs(params) {
1069
+ const searchParams = new URLSearchParams();
1070
+ if (params?.fromDate) {
1071
+ searchParams.set("fromDate", params.fromDate.toISOString());
1072
+ }
1073
+ if (params?.toDate) {
1074
+ searchParams.set("toDate", params.toDate.toISOString());
1075
+ }
1076
+ if (params?.limit) {
1077
+ searchParams.set("limit", String(params.limit));
1078
+ }
1079
+ if (params?.offset) {
1080
+ searchParams.set("offset", String(params.offset));
1081
+ }
1082
+ if (params?.resourceId) {
1083
+ searchParams.set("resourceId", params.resourceId);
1084
+ }
1085
+ if (searchParams.size) {
1086
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1087
+ } else {
1088
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1089
+ }
385
1090
  }
386
1091
  /**
387
- * Creates a new workflow run
1092
+ * Creates a new legacy workflow run
388
1093
  * @returns Promise containing the generated run ID
389
1094
  */
390
1095
  createRun(params) {
@@ -392,34 +1097,34 @@ var Workflow = class extends BaseResource {
392
1097
  if (!!params?.runId) {
393
1098
  searchParams.set("runId", params.runId);
394
1099
  }
395
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1100
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
396
1101
  method: "POST"
397
1102
  });
398
1103
  }
399
1104
  /**
400
- * Starts a workflow run synchronously without waiting for the workflow to complete
1105
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
401
1106
  * @param params - Object containing the runId and triggerData
402
1107
  * @returns Promise containing success message
403
1108
  */
404
1109
  start(params) {
405
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1110
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
406
1111
  method: "POST",
407
1112
  body: params?.triggerData
408
1113
  });
409
1114
  }
410
1115
  /**
411
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1116
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
412
1117
  * @param stepId - ID of the step to resume
413
- * @param runId - ID of the workflow run
414
- * @param context - Context to resume the workflow with
415
- * @returns Promise containing the workflow resume results
1118
+ * @param runId - ID of the legacy workflow run
1119
+ * @param context - Context to resume the legacy workflow with
1120
+ * @returns Promise containing the legacy workflow resume results
416
1121
  */
417
1122
  resume({
418
1123
  stepId,
419
1124
  runId,
420
1125
  context
421
1126
  }) {
422
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1127
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
423
1128
  method: "POST",
424
1129
  body: {
425
1130
  stepId,
@@ -437,18 +1142,18 @@ var Workflow = class extends BaseResource {
437
1142
  if (!!params?.runId) {
438
1143
  searchParams.set("runId", params.runId);
439
1144
  }
440
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1145
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
441
1146
  method: "POST",
442
1147
  body: params?.triggerData
443
1148
  });
444
1149
  }
445
1150
  /**
446
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1151
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
447
1152
  * @param params - Object containing the runId, stepId, and context
448
1153
  * @returns Promise containing the workflow resume results
449
1154
  */
450
1155
  resumeAsync(params) {
451
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1156
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
452
1157
  method: "POST",
453
1158
  body: {
454
1159
  stepId: params.stepId,
@@ -487,7 +1192,7 @@ var Workflow = class extends BaseResource {
487
1192
  }
488
1193
  }
489
1194
  }
490
- } catch (error) {
1195
+ } catch {
491
1196
  }
492
1197
  }
493
1198
  if (buffer) {
@@ -502,16 +1207,16 @@ var Workflow = class extends BaseResource {
502
1207
  }
503
1208
  }
504
1209
  /**
505
- * Watches workflow transitions in real-time
1210
+ * Watches legacy workflow transitions in real-time
506
1211
  * @param runId - Optional run ID to filter the watch stream
507
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1212
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
508
1213
  */
509
1214
  async watch({ runId }, onRecord) {
510
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1215
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
511
1216
  stream: true
512
1217
  });
513
1218
  if (!response.ok) {
514
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1219
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
515
1220
  }
516
1221
  if (!response.body) {
517
1222
  throw new Error("Response body is null");
@@ -523,7 +1228,7 @@ var Workflow = class extends BaseResource {
523
1228
  };
524
1229
 
525
1230
  // src/resources/tool.ts
526
- var Tool = class extends BaseResource {
1231
+ var Tool2 = class extends BaseResource {
527
1232
  constructor(options, toolId) {
528
1233
  super(options);
529
1234
  this.toolId = toolId;
@@ -541,60 +1246,676 @@ var Tool = class extends BaseResource {
541
1246
  * @returns Promise containing the tool execution results
542
1247
  */
543
1248
  execute(params) {
544
- return this.request(`/api/tools/${this.toolId}/execute`, {
1249
+ const url = new URLSearchParams();
1250
+ if (params.runId) {
1251
+ url.set("runId", params.runId);
1252
+ }
1253
+ const body = {
1254
+ data: params.data,
1255
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1256
+ };
1257
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
545
1258
  method: "POST",
546
- body: params
1259
+ body
547
1260
  });
548
1261
  }
549
1262
  };
550
1263
 
551
- // src/client.ts
552
- var MastraClient = class extends BaseResource {
553
- constructor(options) {
1264
+ // src/resources/workflow.ts
1265
+ var RECORD_SEPARATOR2 = "";
1266
+ var Workflow = class extends BaseResource {
1267
+ constructor(options, workflowId) {
554
1268
  super(options);
1269
+ this.workflowId = workflowId;
555
1270
  }
556
1271
  /**
557
- * Retrieves all available agents
558
- * @returns Promise containing map of agent IDs to agent details
1272
+ * Creates an async generator that processes a readable stream and yields workflow records
1273
+ * separated by the Record Separator character (\x1E)
1274
+ *
1275
+ * @param stream - The readable stream to process
1276
+ * @returns An async generator that yields parsed records
559
1277
  */
560
- getAgents() {
561
- return this.request("/api/agents");
1278
+ async *streamProcessor(stream) {
1279
+ const reader = stream.getReader();
1280
+ let doneReading = false;
1281
+ let buffer = "";
1282
+ try {
1283
+ while (!doneReading) {
1284
+ const { done, value } = await reader.read();
1285
+ doneReading = done;
1286
+ if (done && !value) continue;
1287
+ try {
1288
+ const decoded = value ? new TextDecoder().decode(value) : "";
1289
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
1290
+ buffer = chunks.pop() || "";
1291
+ for (const chunk of chunks) {
1292
+ if (chunk) {
1293
+ if (typeof chunk === "string") {
1294
+ try {
1295
+ const parsedChunk = JSON.parse(chunk);
1296
+ yield parsedChunk;
1297
+ } catch {
1298
+ }
1299
+ }
1300
+ }
1301
+ }
1302
+ } catch {
1303
+ }
1304
+ }
1305
+ if (buffer) {
1306
+ try {
1307
+ yield JSON.parse(buffer);
1308
+ } catch {
1309
+ }
1310
+ }
1311
+ } finally {
1312
+ reader.cancel().catch(() => {
1313
+ });
1314
+ }
562
1315
  }
563
1316
  /**
564
- * Gets an agent instance by ID
565
- * @param agentId - ID of the agent to retrieve
566
- * @returns Agent instance
1317
+ * Retrieves details about the workflow
1318
+ * @returns Promise containing workflow details including steps and graphs
567
1319
  */
568
- getAgent(agentId) {
569
- return new Agent(this.options, agentId);
1320
+ details() {
1321
+ return this.request(`/api/workflows/${this.workflowId}`);
570
1322
  }
571
1323
  /**
572
- * Retrieves memory threads for a resource
573
- * @param params - Parameters containing the resource ID
574
- * @returns Promise containing array of memory threads
1324
+ * Retrieves all runs for a workflow
1325
+ * @param params - Parameters for filtering runs
1326
+ * @returns Promise containing workflow runs array
575
1327
  */
576
- getMemoryThreads(params) {
577
- return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1328
+ runs(params) {
1329
+ const searchParams = new URLSearchParams();
1330
+ if (params?.fromDate) {
1331
+ searchParams.set("fromDate", params.fromDate.toISOString());
1332
+ }
1333
+ if (params?.toDate) {
1334
+ searchParams.set("toDate", params.toDate.toISOString());
1335
+ }
1336
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1337
+ searchParams.set("limit", String(params.limit));
1338
+ }
1339
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1340
+ searchParams.set("offset", String(params.offset));
1341
+ }
1342
+ if (params?.resourceId) {
1343
+ searchParams.set("resourceId", params.resourceId);
1344
+ }
1345
+ if (searchParams.size) {
1346
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1347
+ } else {
1348
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1349
+ }
578
1350
  }
579
1351
  /**
580
- * Creates a new memory thread
581
- * @param params - Parameters for creating the memory thread
582
- * @returns Promise containing the created memory thread
1352
+ * Retrieves a specific workflow run by its ID
1353
+ * @param runId - The ID of the workflow run to retrieve
1354
+ * @returns Promise containing the workflow run details
583
1355
  */
584
- createMemoryThread(params) {
585
- return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
1356
+ runById(runId) {
1357
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
586
1358
  }
587
1359
  /**
588
- * Gets a memory thread instance by ID
589
- * @param threadId - ID of the memory thread to retrieve
590
- * @returns MemoryThread instance
1360
+ * Retrieves the execution result for a specific workflow run by its ID
1361
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1362
+ * @returns Promise containing the workflow run execution result
591
1363
  */
592
- getMemoryThread(threadId, agentId) {
593
- return new MemoryThread(this.options, threadId, agentId);
1364
+ runExecutionResult(runId) {
1365
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
594
1366
  }
595
1367
  /**
596
- * Saves messages to memory
597
- * @param params - Parameters containing messages to save
1368
+ * Cancels a specific workflow run by its ID
1369
+ * @param runId - The ID of the workflow run to cancel
1370
+ * @returns Promise containing a success message
1371
+ */
1372
+ cancelRun(runId) {
1373
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1374
+ method: "POST"
1375
+ });
1376
+ }
1377
+ /**
1378
+ * Sends an event to a specific workflow run by its ID
1379
+ * @param params - Object containing the runId, event and data
1380
+ * @returns Promise containing a success message
1381
+ */
1382
+ sendRunEvent(params) {
1383
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1384
+ method: "POST",
1385
+ body: { event: params.event, data: params.data }
1386
+ });
1387
+ }
1388
+ /**
1389
+ * Creates a new workflow run
1390
+ * @param params - Optional object containing the optional runId
1391
+ * @returns Promise containing the runId of the created run
1392
+ */
1393
+ createRun(params) {
1394
+ const searchParams = new URLSearchParams();
1395
+ if (!!params?.runId) {
1396
+ searchParams.set("runId", params.runId);
1397
+ }
1398
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
1399
+ method: "POST"
1400
+ });
1401
+ }
1402
+ /**
1403
+ * Starts a workflow run synchronously without waiting for the workflow to complete
1404
+ * @param params - Object containing the runId, inputData and runtimeContext
1405
+ * @returns Promise containing success message
1406
+ */
1407
+ start(params) {
1408
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1409
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1410
+ method: "POST",
1411
+ body: { inputData: params?.inputData, runtimeContext }
1412
+ });
1413
+ }
1414
+ /**
1415
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1416
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1417
+ * @returns Promise containing success message
1418
+ */
1419
+ resume({
1420
+ step,
1421
+ runId,
1422
+ resumeData,
1423
+ ...rest
1424
+ }) {
1425
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1426
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1427
+ method: "POST",
1428
+ stream: true,
1429
+ body: {
1430
+ step,
1431
+ resumeData,
1432
+ runtimeContext
1433
+ }
1434
+ });
1435
+ }
1436
+ /**
1437
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
1438
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1439
+ * @returns Promise containing the workflow execution results
1440
+ */
1441
+ startAsync(params) {
1442
+ const searchParams = new URLSearchParams();
1443
+ if (!!params?.runId) {
1444
+ searchParams.set("runId", params.runId);
1445
+ }
1446
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1447
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1448
+ method: "POST",
1449
+ body: { inputData: params.inputData, runtimeContext }
1450
+ });
1451
+ }
1452
+ /**
1453
+ * Starts a workflow run and returns a stream
1454
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1455
+ * @returns Promise containing the workflow execution results
1456
+ */
1457
+ async stream(params) {
1458
+ const searchParams = new URLSearchParams();
1459
+ if (!!params?.runId) {
1460
+ searchParams.set("runId", params.runId);
1461
+ }
1462
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1463
+ const response = await this.request(
1464
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1465
+ {
1466
+ method: "POST",
1467
+ body: { inputData: params.inputData, runtimeContext },
1468
+ stream: true
1469
+ }
1470
+ );
1471
+ if (!response.ok) {
1472
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1473
+ }
1474
+ if (!response.body) {
1475
+ throw new Error("Response body is null");
1476
+ }
1477
+ const transformStream = new TransformStream({
1478
+ start() {
1479
+ },
1480
+ async transform(chunk, controller) {
1481
+ try {
1482
+ const decoded = new TextDecoder().decode(chunk);
1483
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1484
+ for (const chunk2 of chunks) {
1485
+ if (chunk2) {
1486
+ try {
1487
+ const parsedChunk = JSON.parse(chunk2);
1488
+ controller.enqueue(parsedChunk);
1489
+ } catch {
1490
+ }
1491
+ }
1492
+ }
1493
+ } catch {
1494
+ }
1495
+ }
1496
+ });
1497
+ return response.body.pipeThrough(transformStream);
1498
+ }
1499
+ /**
1500
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1501
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1502
+ * @returns Promise containing the workflow resume results
1503
+ */
1504
+ resumeAsync(params) {
1505
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1506
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1507
+ method: "POST",
1508
+ body: {
1509
+ step: params.step,
1510
+ resumeData: params.resumeData,
1511
+ runtimeContext
1512
+ }
1513
+ });
1514
+ }
1515
+ /**
1516
+ * Watches workflow transitions in real-time
1517
+ * @param runId - Optional run ID to filter the watch stream
1518
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1519
+ */
1520
+ async watch({ runId }, onRecord) {
1521
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1522
+ stream: true
1523
+ });
1524
+ if (!response.ok) {
1525
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1526
+ }
1527
+ if (!response.body) {
1528
+ throw new Error("Response body is null");
1529
+ }
1530
+ for await (const record of this.streamProcessor(response.body)) {
1531
+ if (typeof record === "string") {
1532
+ onRecord(JSON.parse(record));
1533
+ } else {
1534
+ onRecord(record);
1535
+ }
1536
+ }
1537
+ }
1538
+ /**
1539
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1540
+ * serializing each as JSON and separating them with the record separator (\x1E).
1541
+ *
1542
+ * @param records - An iterable or async iterable of objects to stream
1543
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1544
+ */
1545
+ static createRecordStream(records) {
1546
+ const encoder = new TextEncoder();
1547
+ return new ReadableStream({
1548
+ async start(controller) {
1549
+ try {
1550
+ for await (const record of records) {
1551
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1552
+ controller.enqueue(encoder.encode(json));
1553
+ }
1554
+ controller.close();
1555
+ } catch (err) {
1556
+ controller.error(err);
1557
+ }
1558
+ }
1559
+ });
1560
+ }
1561
+ };
1562
+
1563
+ // src/resources/a2a.ts
1564
+ var A2A = class extends BaseResource {
1565
+ constructor(options, agentId) {
1566
+ super(options);
1567
+ this.agentId = agentId;
1568
+ }
1569
+ /**
1570
+ * Get the agent card with metadata about the agent
1571
+ * @returns Promise containing the agent card information
1572
+ */
1573
+ async getCard() {
1574
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1575
+ }
1576
+ /**
1577
+ * Send a message to the agent and get a response
1578
+ * @param params - Parameters for the task
1579
+ * @returns Promise containing the task response
1580
+ */
1581
+ async sendMessage(params) {
1582
+ const response = await this.request(`/a2a/${this.agentId}`, {
1583
+ method: "POST",
1584
+ body: {
1585
+ method: "tasks/send",
1586
+ params
1587
+ }
1588
+ });
1589
+ return { task: response.result };
1590
+ }
1591
+ /**
1592
+ * Get the status and result of a task
1593
+ * @param params - Parameters for querying the task
1594
+ * @returns Promise containing the task response
1595
+ */
1596
+ async getTask(params) {
1597
+ const response = await this.request(`/a2a/${this.agentId}`, {
1598
+ method: "POST",
1599
+ body: {
1600
+ method: "tasks/get",
1601
+ params
1602
+ }
1603
+ });
1604
+ return response.result;
1605
+ }
1606
+ /**
1607
+ * Cancel a running task
1608
+ * @param params - Parameters identifying the task to cancel
1609
+ * @returns Promise containing the task response
1610
+ */
1611
+ async cancelTask(params) {
1612
+ return this.request(`/a2a/${this.agentId}`, {
1613
+ method: "POST",
1614
+ body: {
1615
+ method: "tasks/cancel",
1616
+ params
1617
+ }
1618
+ });
1619
+ }
1620
+ /**
1621
+ * Send a message and subscribe to streaming updates (not fully implemented)
1622
+ * @param params - Parameters for the task
1623
+ * @returns Promise containing the task response
1624
+ */
1625
+ async sendAndSubscribe(params) {
1626
+ return this.request(`/a2a/${this.agentId}`, {
1627
+ method: "POST",
1628
+ body: {
1629
+ method: "tasks/sendSubscribe",
1630
+ params
1631
+ },
1632
+ stream: true
1633
+ });
1634
+ }
1635
+ };
1636
+
1637
+ // src/resources/mcp-tool.ts
1638
+ var MCPTool = class extends BaseResource {
1639
+ serverId;
1640
+ toolId;
1641
+ constructor(options, serverId, toolId) {
1642
+ super(options);
1643
+ this.serverId = serverId;
1644
+ this.toolId = toolId;
1645
+ }
1646
+ /**
1647
+ * Retrieves details about this specific tool from the MCP server.
1648
+ * @returns Promise containing the tool's information (name, description, schema).
1649
+ */
1650
+ details() {
1651
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1652
+ }
1653
+ /**
1654
+ * Executes this specific tool on the MCP server.
1655
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1656
+ * @returns Promise containing the result of the tool execution.
1657
+ */
1658
+ execute(params) {
1659
+ const body = {};
1660
+ if (params.data !== void 0) body.data = params.data;
1661
+ if (params.runtimeContext !== void 0) {
1662
+ body.runtimeContext = params.runtimeContext;
1663
+ }
1664
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1665
+ method: "POST",
1666
+ body: Object.keys(body).length > 0 ? body : void 0
1667
+ });
1668
+ }
1669
+ };
1670
+
1671
+ // src/resources/network-memory-thread.ts
1672
+ var NetworkMemoryThread = class extends BaseResource {
1673
+ constructor(options, threadId, networkId) {
1674
+ super(options);
1675
+ this.threadId = threadId;
1676
+ this.networkId = networkId;
1677
+ }
1678
+ /**
1679
+ * Retrieves the memory thread details
1680
+ * @returns Promise containing thread details including title and metadata
1681
+ */
1682
+ get() {
1683
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1684
+ }
1685
+ /**
1686
+ * Updates the memory thread properties
1687
+ * @param params - Update parameters including title and metadata
1688
+ * @returns Promise containing updated thread details
1689
+ */
1690
+ update(params) {
1691
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1692
+ method: "PATCH",
1693
+ body: params
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Deletes the memory thread
1698
+ * @returns Promise containing deletion result
1699
+ */
1700
+ delete() {
1701
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1702
+ method: "DELETE"
1703
+ });
1704
+ }
1705
+ /**
1706
+ * Retrieves messages associated with the thread
1707
+ * @param params - Optional parameters including limit for number of messages to retrieve
1708
+ * @returns Promise containing thread messages and UI messages
1709
+ */
1710
+ getMessages(params) {
1711
+ const query = new URLSearchParams({
1712
+ networkId: this.networkId,
1713
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1714
+ });
1715
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1716
+ }
1717
+ };
1718
+
1719
+ // src/resources/vNextNetwork.ts
1720
+ var RECORD_SEPARATOR3 = "";
1721
+ var VNextNetwork = class extends BaseResource {
1722
+ constructor(options, networkId) {
1723
+ super(options);
1724
+ this.networkId = networkId;
1725
+ }
1726
+ /**
1727
+ * Retrieves details about the network
1728
+ * @returns Promise containing vNext network details
1729
+ */
1730
+ details() {
1731
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1732
+ }
1733
+ /**
1734
+ * Generates a response from the v-next network
1735
+ * @param params - Generation parameters including message
1736
+ * @returns Promise containing the generated response
1737
+ */
1738
+ generate(params) {
1739
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1740
+ method: "POST",
1741
+ body: {
1742
+ ...params,
1743
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1744
+ }
1745
+ });
1746
+ }
1747
+ /**
1748
+ * Generates a response from the v-next network using multiple primitives
1749
+ * @param params - Generation parameters including message
1750
+ * @returns Promise containing the generated response
1751
+ */
1752
+ loop(params) {
1753
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1754
+ method: "POST",
1755
+ body: {
1756
+ ...params,
1757
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1758
+ }
1759
+ });
1760
+ }
1761
+ async *streamProcessor(stream) {
1762
+ const reader = stream.getReader();
1763
+ let doneReading = false;
1764
+ let buffer = "";
1765
+ try {
1766
+ while (!doneReading) {
1767
+ const { done, value } = await reader.read();
1768
+ doneReading = done;
1769
+ if (done && !value) continue;
1770
+ try {
1771
+ const decoded = value ? new TextDecoder().decode(value) : "";
1772
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1773
+ buffer = chunks.pop() || "";
1774
+ for (const chunk of chunks) {
1775
+ if (chunk) {
1776
+ if (typeof chunk === "string") {
1777
+ try {
1778
+ const parsedChunk = JSON.parse(chunk);
1779
+ yield parsedChunk;
1780
+ } catch {
1781
+ }
1782
+ }
1783
+ }
1784
+ }
1785
+ } catch {
1786
+ }
1787
+ }
1788
+ if (buffer) {
1789
+ try {
1790
+ yield JSON.parse(buffer);
1791
+ } catch {
1792
+ }
1793
+ }
1794
+ } finally {
1795
+ reader.cancel().catch(() => {
1796
+ });
1797
+ }
1798
+ }
1799
+ /**
1800
+ * Streams a response from the v-next network
1801
+ * @param params - Stream parameters including message
1802
+ * @returns Promise containing the results
1803
+ */
1804
+ async stream(params, onRecord) {
1805
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1806
+ method: "POST",
1807
+ body: {
1808
+ ...params,
1809
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1810
+ },
1811
+ stream: true
1812
+ });
1813
+ if (!response.ok) {
1814
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1815
+ }
1816
+ if (!response.body) {
1817
+ throw new Error("Response body is null");
1818
+ }
1819
+ for await (const record of this.streamProcessor(response.body)) {
1820
+ if (typeof record === "string") {
1821
+ onRecord(JSON.parse(record));
1822
+ } else {
1823
+ onRecord(record);
1824
+ }
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Streams a response from the v-next network loop
1829
+ * @param params - Stream parameters including message
1830
+ * @returns Promise containing the results
1831
+ */
1832
+ async loopStream(params, onRecord) {
1833
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1834
+ method: "POST",
1835
+ body: {
1836
+ ...params,
1837
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1838
+ },
1839
+ stream: true
1840
+ });
1841
+ if (!response.ok) {
1842
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1843
+ }
1844
+ if (!response.body) {
1845
+ throw new Error("Response body is null");
1846
+ }
1847
+ for await (const record of this.streamProcessor(response.body)) {
1848
+ if (typeof record === "string") {
1849
+ onRecord(JSON.parse(record));
1850
+ } else {
1851
+ onRecord(record);
1852
+ }
1853
+ }
1854
+ }
1855
+ };
1856
+
1857
+ // src/client.ts
1858
+ var MastraClient = class extends BaseResource {
1859
+ constructor(options) {
1860
+ super(options);
1861
+ }
1862
+ /**
1863
+ * Retrieves all available agents
1864
+ * @returns Promise containing map of agent IDs to agent details
1865
+ */
1866
+ getAgents() {
1867
+ return this.request("/api/agents");
1868
+ }
1869
+ async getAGUI({ resourceId }) {
1870
+ const agents = await this.getAgents();
1871
+ return Object.entries(agents).reduce(
1872
+ (acc, [agentId]) => {
1873
+ const agent = this.getAgent(agentId);
1874
+ acc[agentId] = new AGUIAdapter({
1875
+ agentId,
1876
+ agent,
1877
+ resourceId
1878
+ });
1879
+ return acc;
1880
+ },
1881
+ {}
1882
+ );
1883
+ }
1884
+ /**
1885
+ * Gets an agent instance by ID
1886
+ * @param agentId - ID of the agent to retrieve
1887
+ * @returns Agent instance
1888
+ */
1889
+ getAgent(agentId) {
1890
+ return new Agent(this.options, agentId);
1891
+ }
1892
+ /**
1893
+ * Retrieves memory threads for a resource
1894
+ * @param params - Parameters containing the resource ID
1895
+ * @returns Promise containing array of memory threads
1896
+ */
1897
+ getMemoryThreads(params) {
1898
+ return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
1899
+ }
1900
+ /**
1901
+ * Creates a new memory thread
1902
+ * @param params - Parameters for creating the memory thread
1903
+ * @returns Promise containing the created memory thread
1904
+ */
1905
+ createMemoryThread(params) {
1906
+ return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
1907
+ }
1908
+ /**
1909
+ * Gets a memory thread instance by ID
1910
+ * @param threadId - ID of the memory thread to retrieve
1911
+ * @returns MemoryThread instance
1912
+ */
1913
+ getMemoryThread(threadId, agentId) {
1914
+ return new MemoryThread(this.options, threadId, agentId);
1915
+ }
1916
+ /**
1917
+ * Saves messages to memory
1918
+ * @param params - Parameters containing messages to save
598
1919
  * @returns Promise containing the saved messages
599
1920
  */
600
1921
  saveMessageToMemory(params) {
@@ -610,6 +1931,48 @@ var MastraClient = class extends BaseResource {
610
1931
  getMemoryStatus(agentId) {
611
1932
  return this.request(`/api/memory/status?agentId=${agentId}`);
612
1933
  }
1934
+ /**
1935
+ * Retrieves memory threads for a resource
1936
+ * @param params - Parameters containing the resource ID
1937
+ * @returns Promise containing array of memory threads
1938
+ */
1939
+ getNetworkMemoryThreads(params) {
1940
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1941
+ }
1942
+ /**
1943
+ * Creates a new memory thread
1944
+ * @param params - Parameters for creating the memory thread
1945
+ * @returns Promise containing the created memory thread
1946
+ */
1947
+ createNetworkMemoryThread(params) {
1948
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1949
+ }
1950
+ /**
1951
+ * Gets a memory thread instance by ID
1952
+ * @param threadId - ID of the memory thread to retrieve
1953
+ * @returns MemoryThread instance
1954
+ */
1955
+ getNetworkMemoryThread(threadId, networkId) {
1956
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1957
+ }
1958
+ /**
1959
+ * Saves messages to memory
1960
+ * @param params - Parameters containing messages to save
1961
+ * @returns Promise containing the saved messages
1962
+ */
1963
+ saveNetworkMessageToMemory(params) {
1964
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1965
+ method: "POST",
1966
+ body: params
1967
+ });
1968
+ }
1969
+ /**
1970
+ * Gets the status of the memory system
1971
+ * @returns Promise containing memory system status
1972
+ */
1973
+ getNetworkMemoryStatus(networkId) {
1974
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1975
+ }
613
1976
  /**
614
1977
  * Retrieves all available tools
615
1978
  * @returns Promise containing map of tool IDs to tool details
@@ -623,7 +1986,22 @@ var MastraClient = class extends BaseResource {
623
1986
  * @returns Tool instance
624
1987
  */
625
1988
  getTool(toolId) {
626
- return new Tool(this.options, toolId);
1989
+ return new Tool2(this.options, toolId);
1990
+ }
1991
+ /**
1992
+ * Retrieves all available legacy workflows
1993
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1994
+ */
1995
+ getLegacyWorkflows() {
1996
+ return this.request("/api/workflows/legacy");
1997
+ }
1998
+ /**
1999
+ * Gets a legacy workflow instance by ID
2000
+ * @param workflowId - ID of the legacy workflow to retrieve
2001
+ * @returns Legacy Workflow instance
2002
+ */
2003
+ getLegacyWorkflow(workflowId) {
2004
+ return new LegacyWorkflow(this.options, workflowId);
627
2005
  }
628
2006
  /**
629
2007
  * Retrieves all available workflows
@@ -654,7 +2032,41 @@ var MastraClient = class extends BaseResource {
654
2032
  * @returns Promise containing array of log messages
655
2033
  */
656
2034
  getLogs(params) {
657
- return this.request(`/api/logs?transportId=${params.transportId}`);
2035
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2036
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2037
+ const searchParams = new URLSearchParams();
2038
+ if (transportId) {
2039
+ searchParams.set("transportId", transportId);
2040
+ }
2041
+ if (fromDate) {
2042
+ searchParams.set("fromDate", fromDate.toISOString());
2043
+ }
2044
+ if (toDate) {
2045
+ searchParams.set("toDate", toDate.toISOString());
2046
+ }
2047
+ if (logLevel) {
2048
+ searchParams.set("logLevel", logLevel);
2049
+ }
2050
+ if (page) {
2051
+ searchParams.set("page", String(page));
2052
+ }
2053
+ if (perPage) {
2054
+ searchParams.set("perPage", String(perPage));
2055
+ }
2056
+ if (_filters) {
2057
+ if (Array.isArray(_filters)) {
2058
+ for (const filter of _filters) {
2059
+ searchParams.append("filters", filter);
2060
+ }
2061
+ } else {
2062
+ searchParams.set("filters", _filters);
2063
+ }
2064
+ }
2065
+ if (searchParams.size) {
2066
+ return this.request(`/api/logs?${searchParams}`);
2067
+ } else {
2068
+ return this.request(`/api/logs`);
2069
+ }
658
2070
  }
659
2071
  /**
660
2072
  * Gets logs for a specific run
@@ -662,7 +2074,44 @@ var MastraClient = class extends BaseResource {
662
2074
  * @returns Promise containing array of log messages
663
2075
  */
664
2076
  getLogForRun(params) {
665
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2077
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2078
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2079
+ const searchParams = new URLSearchParams();
2080
+ if (runId) {
2081
+ searchParams.set("runId", runId);
2082
+ }
2083
+ if (transportId) {
2084
+ searchParams.set("transportId", transportId);
2085
+ }
2086
+ if (fromDate) {
2087
+ searchParams.set("fromDate", fromDate.toISOString());
2088
+ }
2089
+ if (toDate) {
2090
+ searchParams.set("toDate", toDate.toISOString());
2091
+ }
2092
+ if (logLevel) {
2093
+ searchParams.set("logLevel", logLevel);
2094
+ }
2095
+ if (page) {
2096
+ searchParams.set("page", String(page));
2097
+ }
2098
+ if (perPage) {
2099
+ searchParams.set("perPage", String(perPage));
2100
+ }
2101
+ if (_filters) {
2102
+ if (Array.isArray(_filters)) {
2103
+ for (const filter of _filters) {
2104
+ searchParams.append("filters", filter);
2105
+ }
2106
+ } else {
2107
+ searchParams.set("filters", _filters);
2108
+ }
2109
+ }
2110
+ if (searchParams.size) {
2111
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2112
+ } else {
2113
+ return this.request(`/api/logs/${runId}`);
2114
+ }
666
2115
  }
667
2116
  /**
668
2117
  * List of all log transports
@@ -677,7 +2126,7 @@ var MastraClient = class extends BaseResource {
677
2126
  * @returns Promise containing telemetry data
678
2127
  */
679
2128
  getTelemetry(params) {
680
- const { name, scope, page, perPage, attribute } = params || {};
2129
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
681
2130
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
682
2131
  const searchParams = new URLSearchParams();
683
2132
  if (name) {
@@ -701,6 +2150,12 @@ var MastraClient = class extends BaseResource {
701
2150
  searchParams.set("attribute", _attribute);
702
2151
  }
703
2152
  }
2153
+ if (fromDate) {
2154
+ searchParams.set("fromDate", fromDate.toISOString());
2155
+ }
2156
+ if (toDate) {
2157
+ searchParams.set("toDate", toDate.toISOString());
2158
+ }
704
2159
  if (searchParams.size) {
705
2160
  return this.request(`/api/telemetry?${searchParams}`);
706
2161
  } else {
@@ -714,6 +2169,13 @@ var MastraClient = class extends BaseResource {
714
2169
  getNetworks() {
715
2170
  return this.request("/api/networks");
716
2171
  }
2172
+ /**
2173
+ * Retrieves all available vNext networks
2174
+ * @returns Promise containing map of vNext network IDs to vNext network details
2175
+ */
2176
+ getVNextNetworks() {
2177
+ return this.request("/api/networks/v-next");
2178
+ }
717
2179
  /**
718
2180
  * Gets a network instance by ID
719
2181
  * @param networkId - ID of the network to retrieve
@@ -722,6 +2184,105 @@ var MastraClient = class extends BaseResource {
722
2184
  getNetwork(networkId) {
723
2185
  return new Network(this.options, networkId);
724
2186
  }
2187
+ /**
2188
+ * Gets a vNext network instance by ID
2189
+ * @param networkId - ID of the vNext network to retrieve
2190
+ * @returns vNext Network instance
2191
+ */
2192
+ getVNextNetwork(networkId) {
2193
+ return new VNextNetwork(this.options, networkId);
2194
+ }
2195
+ /**
2196
+ * Retrieves a list of available MCP servers.
2197
+ * @param params - Optional parameters for pagination (limit, offset).
2198
+ * @returns Promise containing the list of MCP servers and pagination info.
2199
+ */
2200
+ getMcpServers(params) {
2201
+ const searchParams = new URLSearchParams();
2202
+ if (params?.limit !== void 0) {
2203
+ searchParams.set("limit", String(params.limit));
2204
+ }
2205
+ if (params?.offset !== void 0) {
2206
+ searchParams.set("offset", String(params.offset));
2207
+ }
2208
+ const queryString = searchParams.toString();
2209
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2210
+ }
2211
+ /**
2212
+ * Retrieves detailed information for a specific MCP server.
2213
+ * @param serverId - The ID of the MCP server to retrieve.
2214
+ * @param params - Optional parameters, e.g., specific version.
2215
+ * @returns Promise containing the detailed MCP server information.
2216
+ */
2217
+ getMcpServerDetails(serverId, params) {
2218
+ const searchParams = new URLSearchParams();
2219
+ if (params?.version) {
2220
+ searchParams.set("version", params.version);
2221
+ }
2222
+ const queryString = searchParams.toString();
2223
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2224
+ }
2225
+ /**
2226
+ * Retrieves a list of tools for a specific MCP server.
2227
+ * @param serverId - The ID of the MCP server.
2228
+ * @returns Promise containing the list of tools.
2229
+ */
2230
+ getMcpServerTools(serverId) {
2231
+ return this.request(`/api/mcp/${serverId}/tools`);
2232
+ }
2233
+ /**
2234
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2235
+ * This instance can then be used to fetch details or execute the tool.
2236
+ * @param serverId - The ID of the MCP server.
2237
+ * @param toolId - The ID of the tool.
2238
+ * @returns MCPTool instance.
2239
+ */
2240
+ getMcpServerTool(serverId, toolId) {
2241
+ return new MCPTool(this.options, serverId, toolId);
2242
+ }
2243
+ /**
2244
+ * Gets an A2A client for interacting with an agent via the A2A protocol
2245
+ * @param agentId - ID of the agent to interact with
2246
+ * @returns A2A client instance
2247
+ */
2248
+ getA2A(agentId) {
2249
+ return new A2A(this.options, agentId);
2250
+ }
2251
+ /**
2252
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2253
+ * @param agentId - ID of the agent.
2254
+ * @param threadId - ID of the thread.
2255
+ * @param resourceId - Optional ID of the resource.
2256
+ * @returns Working memory for the specified thread or resource.
2257
+ */
2258
+ getWorkingMemory({
2259
+ agentId,
2260
+ threadId,
2261
+ resourceId
2262
+ }) {
2263
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2264
+ }
2265
+ /**
2266
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2267
+ * @param agentId - ID of the agent.
2268
+ * @param threadId - ID of the thread.
2269
+ * @param workingMemory - The new working memory content.
2270
+ * @param resourceId - Optional ID of the resource.
2271
+ */
2272
+ updateWorkingMemory({
2273
+ agentId,
2274
+ threadId,
2275
+ workingMemory,
2276
+ resourceId
2277
+ }) {
2278
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2279
+ method: "POST",
2280
+ body: {
2281
+ workingMemory,
2282
+ resourceId
2283
+ }
2284
+ });
2285
+ }
725
2286
  };
726
2287
 
727
2288
  export { MastraClient };