@mastra/client-js 0.0.0-separate-trace-data-from-component-20250501141108 → 0.0.0-share-agent-metadata-with-cloud-20250718110128

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 { processDataStream } from '@ai-sdk/ui-utils';
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
+ import { processTextStream, processDataStream, parsePartialJson } from '@ai-sdk/ui-utils';
2
4
  import { ZodSchema } from 'zod';
3
- import { zodToJsonSchema } from 'zod-to-json-schema';
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,41 +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
- * Retrieves all runs for a workflow
376
- * @returns Promise containing workflow runs array
377
- */
378
- runs() {
379
- return this.request(`/api/workflows/${this.workflowId}/runs`);
380
- }
381
- /**
382
- * @deprecated Use `startAsync` instead
383
- * Executes the workflow with the provided parameters
384
- * @param params - Parameters required for workflow execution
385
- * @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
386
1067
  */
387
- execute(params) {
388
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
389
- method: "POST",
390
- body: params
391
- });
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
+ }
392
1090
  }
393
1091
  /**
394
- * Creates a new workflow run
1092
+ * Creates a new legacy workflow run
395
1093
  * @returns Promise containing the generated run ID
396
1094
  */
397
1095
  createRun(params) {
@@ -399,34 +1097,34 @@ var Workflow = class extends BaseResource {
399
1097
  if (!!params?.runId) {
400
1098
  searchParams.set("runId", params.runId);
401
1099
  }
402
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1100
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
403
1101
  method: "POST"
404
1102
  });
405
1103
  }
406
1104
  /**
407
- * 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
408
1106
  * @param params - Object containing the runId and triggerData
409
1107
  * @returns Promise containing success message
410
1108
  */
411
1109
  start(params) {
412
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1110
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
413
1111
  method: "POST",
414
1112
  body: params?.triggerData
415
1113
  });
416
1114
  }
417
1115
  /**
418
- * 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
419
1117
  * @param stepId - ID of the step to resume
420
- * @param runId - ID of the workflow run
421
- * @param context - Context to resume the workflow with
422
- * @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
423
1121
  */
424
1122
  resume({
425
1123
  stepId,
426
1124
  runId,
427
1125
  context
428
1126
  }) {
429
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1127
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
430
1128
  method: "POST",
431
1129
  body: {
432
1130
  stepId,
@@ -444,18 +1142,18 @@ var Workflow = class extends BaseResource {
444
1142
  if (!!params?.runId) {
445
1143
  searchParams.set("runId", params.runId);
446
1144
  }
447
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1145
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
448
1146
  method: "POST",
449
1147
  body: params?.triggerData
450
1148
  });
451
1149
  }
452
1150
  /**
453
- * 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
454
1152
  * @param params - Object containing the runId, stepId, and context
455
1153
  * @returns Promise containing the workflow resume results
456
1154
  */
457
1155
  resumeAsync(params) {
458
- 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}`, {
459
1157
  method: "POST",
460
1158
  body: {
461
1159
  stepId: params.stepId,
@@ -509,16 +1207,16 @@ var Workflow = class extends BaseResource {
509
1207
  }
510
1208
  }
511
1209
  /**
512
- * Watches workflow transitions in real-time
1210
+ * Watches legacy workflow transitions in real-time
513
1211
  * @param runId - Optional run ID to filter the watch stream
514
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1212
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
515
1213
  */
516
1214
  async watch({ runId }, onRecord) {
517
- 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}`, {
518
1216
  stream: true
519
1217
  });
520
1218
  if (!response.ok) {
521
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1219
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
522
1220
  }
523
1221
  if (!response.body) {
524
1222
  throw new Error("Response body is null");
@@ -530,7 +1228,7 @@ var Workflow = class extends BaseResource {
530
1228
  };
531
1229
 
532
1230
  // src/resources/tool.ts
533
- var Tool = class extends BaseResource {
1231
+ var Tool2 = class extends BaseResource {
534
1232
  constructor(options, toolId) {
535
1233
  super(options);
536
1234
  this.toolId = toolId;
@@ -552,22 +1250,26 @@ var Tool = class extends BaseResource {
552
1250
  if (params.runId) {
553
1251
  url.set("runId", params.runId);
554
1252
  }
1253
+ const body = {
1254
+ data: params.data,
1255
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1256
+ };
555
1257
  return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
556
1258
  method: "POST",
557
- body: params.data
1259
+ body
558
1260
  });
559
1261
  }
560
1262
  };
561
1263
 
562
- // src/resources/vnext-workflow.ts
1264
+ // src/resources/workflow.ts
563
1265
  var RECORD_SEPARATOR2 = "";
564
- var VNextWorkflow = class extends BaseResource {
1266
+ var Workflow = class extends BaseResource {
565
1267
  constructor(options, workflowId) {
566
1268
  super(options);
567
1269
  this.workflowId = workflowId;
568
1270
  }
569
1271
  /**
570
- * Creates an async generator that processes a readable stream and yields vNext workflow records
1272
+ * Creates an async generator that processes a readable stream and yields workflow records
571
1273
  * separated by the Record Separator character (\x1E)
572
1274
  *
573
1275
  * @param stream - The readable stream to process
@@ -612,21 +1314,79 @@ var VNextWorkflow = class extends BaseResource {
612
1314
  }
613
1315
  }
614
1316
  /**
615
- * Retrieves details about the vNext workflow
616
- * @returns Promise containing vNext workflow details including steps and graphs
1317
+ * Retrieves details about the workflow
1318
+ * @returns Promise containing workflow details including steps and graphs
617
1319
  */
618
1320
  details() {
619
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1321
+ return this.request(`/api/workflows/${this.workflowId}`);
1322
+ }
1323
+ /**
1324
+ * Retrieves all runs for a workflow
1325
+ * @param params - Parameters for filtering runs
1326
+ * @returns Promise containing workflow runs array
1327
+ */
1328
+ runs(params) {
1329
+ const searchParams = new URLSearchParams();
1330
+ if (params?.fromDate) {
1331
+ searchParams.set("fromDate", params.fromDate.toISOString());
1332
+ }
1333
+ if (params?.toDate) {
1334
+ searchParams.set("toDate", params.toDate.toISOString());
1335
+ }
1336
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1337
+ searchParams.set("limit", String(params.limit));
1338
+ }
1339
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1340
+ searchParams.set("offset", String(params.offset));
1341
+ }
1342
+ if (params?.resourceId) {
1343
+ searchParams.set("resourceId", params.resourceId);
1344
+ }
1345
+ if (searchParams.size) {
1346
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1347
+ } else {
1348
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Retrieves a specific workflow run by its ID
1353
+ * @param runId - The ID of the workflow run to retrieve
1354
+ * @returns Promise containing the workflow run details
1355
+ */
1356
+ runById(runId) {
1357
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1358
+ }
1359
+ /**
1360
+ * Retrieves the execution result for a specific workflow run by its ID
1361
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1362
+ * @returns Promise containing the workflow run execution result
1363
+ */
1364
+ runExecutionResult(runId) {
1365
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1366
+ }
1367
+ /**
1368
+ * Cancels a specific workflow run by its ID
1369
+ * @param runId - The ID of the workflow run to cancel
1370
+ * @returns Promise containing a success message
1371
+ */
1372
+ cancelRun(runId) {
1373
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1374
+ method: "POST"
1375
+ });
620
1376
  }
621
1377
  /**
622
- * Retrieves all runs for a vNext workflow
623
- * @returns Promise containing vNext workflow runs array
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
624
1381
  */
625
- runs() {
626
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
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
+ });
627
1387
  }
628
1388
  /**
629
- * Creates a new vNext workflow run
1389
+ * Creates a new workflow run
630
1390
  * @param params - Optional object containing the optional runId
631
1391
  * @returns Promise containing the runId of the created run
632
1392
  */
@@ -635,23 +1395,24 @@ var VNextWorkflow = class extends BaseResource {
635
1395
  if (!!params?.runId) {
636
1396
  searchParams.set("runId", params.runId);
637
1397
  }
638
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
1398
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
639
1399
  method: "POST"
640
1400
  });
641
1401
  }
642
1402
  /**
643
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
1403
+ * Starts a workflow run synchronously without waiting for the workflow to complete
644
1404
  * @param params - Object containing the runId, inputData and runtimeContext
645
1405
  * @returns Promise containing success message
646
1406
  */
647
1407
  start(params) {
648
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1408
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1409
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
649
1410
  method: "POST",
650
- body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
1411
+ body: { inputData: params?.inputData, runtimeContext }
651
1412
  });
652
1413
  }
653
1414
  /**
654
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
1415
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
655
1416
  * @param params - Object containing the runId, step, resumeData and runtimeContext
656
1417
  * @returns Promise containing success message
657
1418
  */
@@ -659,9 +1420,10 @@ var VNextWorkflow = class extends BaseResource {
659
1420
  step,
660
1421
  runId,
661
1422
  resumeData,
662
- runtimeContext
1423
+ ...rest
663
1424
  }) {
664
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1425
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1426
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
665
1427
  method: "POST",
666
1428
  stream: true,
667
1429
  body: {
@@ -672,68 +1434,457 @@ var VNextWorkflow = class extends BaseResource {
672
1434
  });
673
1435
  }
674
1436
  /**
675
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
1437
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
676
1438
  * @param params - Object containing the optional runId, inputData and runtimeContext
677
- * @returns Promise containing the vNext workflow execution results
1439
+ * @returns Promise containing the workflow execution results
678
1440
  */
679
1441
  startAsync(params) {
680
1442
  const searchParams = new URLSearchParams();
681
1443
  if (!!params?.runId) {
682
1444
  searchParams.set("runId", params.runId);
683
1445
  }
684
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1446
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1447
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
685
1448
  method: "POST",
686
- body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
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
+ let failedChunk = void 0;
1478
+ const transformStream = new TransformStream({
1479
+ start() {
1480
+ },
1481
+ async transform(chunk, controller) {
1482
+ try {
1483
+ const decoded = new TextDecoder().decode(chunk);
1484
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1485
+ for (const chunk2 of chunks) {
1486
+ if (chunk2) {
1487
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1488
+ try {
1489
+ const parsedChunk = JSON.parse(newChunk);
1490
+ controller.enqueue(parsedChunk);
1491
+ failedChunk = void 0;
1492
+ } catch (error) {
1493
+ failedChunk = newChunk;
1494
+ }
1495
+ }
1496
+ }
1497
+ } catch {
1498
+ }
1499
+ }
687
1500
  });
1501
+ return response.body.pipeThrough(transformStream);
688
1502
  }
689
1503
  /**
690
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
1504
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
691
1505
  * @param params - Object containing the runId, step, resumeData and runtimeContext
692
- * @returns Promise containing the vNext workflow resume results
1506
+ * @returns Promise containing the workflow resume results
693
1507
  */
694
1508
  resumeAsync(params) {
695
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
1509
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1510
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
696
1511
  method: "POST",
697
1512
  body: {
698
1513
  step: params.step,
699
1514
  resumeData: params.resumeData,
700
- runtimeContext: params.runtimeContext
1515
+ runtimeContext
701
1516
  }
702
1517
  });
703
1518
  }
704
1519
  /**
705
- * Watches vNext workflow transitions in real-time
1520
+ * Watches workflow transitions in real-time
706
1521
  * @param runId - Optional run ID to filter the watch stream
707
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
1522
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
708
1523
  */
709
1524
  async watch({ runId }, onRecord) {
710
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
1525
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
711
1526
  stream: true
712
1527
  });
713
1528
  if (!response.ok) {
714
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1529
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
715
1530
  }
716
1531
  if (!response.body) {
717
1532
  throw new Error("Response body is null");
718
1533
  }
719
1534
  for await (const record of this.streamProcessor(response.body)) {
720
- onRecord(record);
1535
+ if (typeof record === "string") {
1536
+ onRecord(JSON.parse(record));
1537
+ } else {
1538
+ onRecord(record);
1539
+ }
721
1540
  }
722
1541
  }
723
- };
724
-
725
- // src/client.ts
726
- var MastraClient = class extends BaseResource {
727
- constructor(options) {
728
- super(options);
729
- }
730
1542
  /**
731
- * Retrieves all available agents
732
- * @returns Promise containing map of agent IDs to agent details
1543
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1544
+ * serializing each as JSON and separating them with the record separator (\x1E).
1545
+ *
1546
+ * @param records - An iterable or async iterable of objects to stream
1547
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
733
1548
  */
734
- getAgents() {
1549
+ static createRecordStream(records) {
1550
+ const encoder = new TextEncoder();
1551
+ return new ReadableStream({
1552
+ async start(controller) {
1553
+ try {
1554
+ for await (const record of records) {
1555
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1556
+ controller.enqueue(encoder.encode(json));
1557
+ }
1558
+ controller.close();
1559
+ } catch (err) {
1560
+ controller.error(err);
1561
+ }
1562
+ }
1563
+ });
1564
+ }
1565
+ };
1566
+
1567
+ // src/resources/a2a.ts
1568
+ var A2A = class extends BaseResource {
1569
+ constructor(options, agentId) {
1570
+ super(options);
1571
+ this.agentId = agentId;
1572
+ }
1573
+ /**
1574
+ * Get the agent card with metadata about the agent
1575
+ * @returns Promise containing the agent card information
1576
+ */
1577
+ async getCard() {
1578
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1579
+ }
1580
+ /**
1581
+ * Send a message to the agent and get a response
1582
+ * @param params - Parameters for the task
1583
+ * @returns Promise containing the task response
1584
+ */
1585
+ async sendMessage(params) {
1586
+ const response = await this.request(`/a2a/${this.agentId}`, {
1587
+ method: "POST",
1588
+ body: {
1589
+ method: "tasks/send",
1590
+ params
1591
+ }
1592
+ });
1593
+ return { task: response.result };
1594
+ }
1595
+ /**
1596
+ * Get the status and result of a task
1597
+ * @param params - Parameters for querying the task
1598
+ * @returns Promise containing the task response
1599
+ */
1600
+ async getTask(params) {
1601
+ const response = await this.request(`/a2a/${this.agentId}`, {
1602
+ method: "POST",
1603
+ body: {
1604
+ method: "tasks/get",
1605
+ params
1606
+ }
1607
+ });
1608
+ return response.result;
1609
+ }
1610
+ /**
1611
+ * Cancel a running task
1612
+ * @param params - Parameters identifying the task to cancel
1613
+ * @returns Promise containing the task response
1614
+ */
1615
+ async cancelTask(params) {
1616
+ return this.request(`/a2a/${this.agentId}`, {
1617
+ method: "POST",
1618
+ body: {
1619
+ method: "tasks/cancel",
1620
+ params
1621
+ }
1622
+ });
1623
+ }
1624
+ /**
1625
+ * Send a message and subscribe to streaming updates (not fully implemented)
1626
+ * @param params - Parameters for the task
1627
+ * @returns Promise containing the task response
1628
+ */
1629
+ async sendAndSubscribe(params) {
1630
+ return this.request(`/a2a/${this.agentId}`, {
1631
+ method: "POST",
1632
+ body: {
1633
+ method: "tasks/sendSubscribe",
1634
+ params
1635
+ },
1636
+ stream: true
1637
+ });
1638
+ }
1639
+ };
1640
+
1641
+ // src/resources/mcp-tool.ts
1642
+ var MCPTool = class extends BaseResource {
1643
+ serverId;
1644
+ toolId;
1645
+ constructor(options, serverId, toolId) {
1646
+ super(options);
1647
+ this.serverId = serverId;
1648
+ this.toolId = toolId;
1649
+ }
1650
+ /**
1651
+ * Retrieves details about this specific tool from the MCP server.
1652
+ * @returns Promise containing the tool's information (name, description, schema).
1653
+ */
1654
+ details() {
1655
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1656
+ }
1657
+ /**
1658
+ * Executes this specific tool on the MCP server.
1659
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1660
+ * @returns Promise containing the result of the tool execution.
1661
+ */
1662
+ execute(params) {
1663
+ const body = {};
1664
+ if (params.data !== void 0) body.data = params.data;
1665
+ if (params.runtimeContext !== void 0) {
1666
+ body.runtimeContext = params.runtimeContext;
1667
+ }
1668
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1669
+ method: "POST",
1670
+ body: Object.keys(body).length > 0 ? body : void 0
1671
+ });
1672
+ }
1673
+ };
1674
+
1675
+ // src/resources/network-memory-thread.ts
1676
+ var NetworkMemoryThread = class extends BaseResource {
1677
+ constructor(options, threadId, networkId) {
1678
+ super(options);
1679
+ this.threadId = threadId;
1680
+ this.networkId = networkId;
1681
+ }
1682
+ /**
1683
+ * Retrieves the memory thread details
1684
+ * @returns Promise containing thread details including title and metadata
1685
+ */
1686
+ get() {
1687
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1688
+ }
1689
+ /**
1690
+ * Updates the memory thread properties
1691
+ * @param params - Update parameters including title and metadata
1692
+ * @returns Promise containing updated thread details
1693
+ */
1694
+ update(params) {
1695
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1696
+ method: "PATCH",
1697
+ body: params
1698
+ });
1699
+ }
1700
+ /**
1701
+ * Deletes the memory thread
1702
+ * @returns Promise containing deletion result
1703
+ */
1704
+ delete() {
1705
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1706
+ method: "DELETE"
1707
+ });
1708
+ }
1709
+ /**
1710
+ * Retrieves messages associated with the thread
1711
+ * @param params - Optional parameters including limit for number of messages to retrieve
1712
+ * @returns Promise containing thread messages and UI messages
1713
+ */
1714
+ getMessages(params) {
1715
+ const query = new URLSearchParams({
1716
+ networkId: this.networkId,
1717
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1718
+ });
1719
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1720
+ }
1721
+ };
1722
+
1723
+ // src/resources/vNextNetwork.ts
1724
+ var RECORD_SEPARATOR3 = "";
1725
+ var VNextNetwork = class extends BaseResource {
1726
+ constructor(options, networkId) {
1727
+ super(options);
1728
+ this.networkId = networkId;
1729
+ }
1730
+ /**
1731
+ * Retrieves details about the network
1732
+ * @returns Promise containing vNext network details
1733
+ */
1734
+ details() {
1735
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1736
+ }
1737
+ /**
1738
+ * Generates a response from the v-next network
1739
+ * @param params - Generation parameters including message
1740
+ * @returns Promise containing the generated response
1741
+ */
1742
+ generate(params) {
1743
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1744
+ method: "POST",
1745
+ body: {
1746
+ ...params,
1747
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1748
+ }
1749
+ });
1750
+ }
1751
+ /**
1752
+ * Generates a response from the v-next network using multiple primitives
1753
+ * @param params - Generation parameters including message
1754
+ * @returns Promise containing the generated response
1755
+ */
1756
+ loop(params) {
1757
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1758
+ method: "POST",
1759
+ body: {
1760
+ ...params,
1761
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1762
+ }
1763
+ });
1764
+ }
1765
+ async *streamProcessor(stream) {
1766
+ const reader = stream.getReader();
1767
+ let doneReading = false;
1768
+ let buffer = "";
1769
+ try {
1770
+ while (!doneReading) {
1771
+ const { done, value } = await reader.read();
1772
+ doneReading = done;
1773
+ if (done && !value) continue;
1774
+ try {
1775
+ const decoded = value ? new TextDecoder().decode(value) : "";
1776
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1777
+ buffer = chunks.pop() || "";
1778
+ for (const chunk of chunks) {
1779
+ if (chunk) {
1780
+ if (typeof chunk === "string") {
1781
+ try {
1782
+ const parsedChunk = JSON.parse(chunk);
1783
+ yield parsedChunk;
1784
+ } catch {
1785
+ }
1786
+ }
1787
+ }
1788
+ }
1789
+ } catch {
1790
+ }
1791
+ }
1792
+ if (buffer) {
1793
+ try {
1794
+ yield JSON.parse(buffer);
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ } finally {
1799
+ reader.cancel().catch(() => {
1800
+ });
1801
+ }
1802
+ }
1803
+ /**
1804
+ * Streams a response from the v-next network
1805
+ * @param params - Stream parameters including message
1806
+ * @returns Promise containing the results
1807
+ */
1808
+ async stream(params, onRecord) {
1809
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1810
+ method: "POST",
1811
+ body: {
1812
+ ...params,
1813
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1814
+ },
1815
+ stream: true
1816
+ });
1817
+ if (!response.ok) {
1818
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1819
+ }
1820
+ if (!response.body) {
1821
+ throw new Error("Response body is null");
1822
+ }
1823
+ for await (const record of this.streamProcessor(response.body)) {
1824
+ if (typeof record === "string") {
1825
+ onRecord(JSON.parse(record));
1826
+ } else {
1827
+ onRecord(record);
1828
+ }
1829
+ }
1830
+ }
1831
+ /**
1832
+ * Streams a response from the v-next network loop
1833
+ * @param params - Stream parameters including message
1834
+ * @returns Promise containing the results
1835
+ */
1836
+ async loopStream(params, onRecord) {
1837
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1838
+ method: "POST",
1839
+ body: {
1840
+ ...params,
1841
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1842
+ },
1843
+ stream: true
1844
+ });
1845
+ if (!response.ok) {
1846
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1847
+ }
1848
+ if (!response.body) {
1849
+ throw new Error("Response body is null");
1850
+ }
1851
+ for await (const record of this.streamProcessor(response.body)) {
1852
+ if (typeof record === "string") {
1853
+ onRecord(JSON.parse(record));
1854
+ } else {
1855
+ onRecord(record);
1856
+ }
1857
+ }
1858
+ }
1859
+ };
1860
+
1861
+ // src/client.ts
1862
+ var MastraClient = class extends BaseResource {
1863
+ constructor(options) {
1864
+ super(options);
1865
+ }
1866
+ /**
1867
+ * Retrieves all available agents
1868
+ * @returns Promise containing map of agent IDs to agent details
1869
+ */
1870
+ getAgents() {
735
1871
  return this.request("/api/agents");
736
1872
  }
1873
+ async getAGUI({ resourceId }) {
1874
+ const agents = await this.getAgents();
1875
+ return Object.entries(agents).reduce(
1876
+ (acc, [agentId]) => {
1877
+ const agent = this.getAgent(agentId);
1878
+ acc[agentId] = new AGUIAdapter({
1879
+ agentId,
1880
+ agent,
1881
+ resourceId
1882
+ });
1883
+ return acc;
1884
+ },
1885
+ {}
1886
+ );
1887
+ }
737
1888
  /**
738
1889
  * Gets an agent instance by ID
739
1890
  * @param agentId - ID of the agent to retrieve
@@ -784,6 +1935,48 @@ var MastraClient = class extends BaseResource {
784
1935
  getMemoryStatus(agentId) {
785
1936
  return this.request(`/api/memory/status?agentId=${agentId}`);
786
1937
  }
1938
+ /**
1939
+ * Retrieves memory threads for a resource
1940
+ * @param params - Parameters containing the resource ID
1941
+ * @returns Promise containing array of memory threads
1942
+ */
1943
+ getNetworkMemoryThreads(params) {
1944
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1945
+ }
1946
+ /**
1947
+ * Creates a new memory thread
1948
+ * @param params - Parameters for creating the memory thread
1949
+ * @returns Promise containing the created memory thread
1950
+ */
1951
+ createNetworkMemoryThread(params) {
1952
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1953
+ }
1954
+ /**
1955
+ * Gets a memory thread instance by ID
1956
+ * @param threadId - ID of the memory thread to retrieve
1957
+ * @returns MemoryThread instance
1958
+ */
1959
+ getNetworkMemoryThread(threadId, networkId) {
1960
+ return new NetworkMemoryThread(this.options, threadId, networkId);
1961
+ }
1962
+ /**
1963
+ * Saves messages to memory
1964
+ * @param params - Parameters containing messages to save
1965
+ * @returns Promise containing the saved messages
1966
+ */
1967
+ saveNetworkMessageToMemory(params) {
1968
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
1969
+ method: "POST",
1970
+ body: params
1971
+ });
1972
+ }
1973
+ /**
1974
+ * Gets the status of the memory system
1975
+ * @returns Promise containing memory system status
1976
+ */
1977
+ getNetworkMemoryStatus(networkId) {
1978
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
1979
+ }
787
1980
  /**
788
1981
  * Retrieves all available tools
789
1982
  * @returns Promise containing map of tool IDs to tool details
@@ -797,7 +1990,22 @@ var MastraClient = class extends BaseResource {
797
1990
  * @returns Tool instance
798
1991
  */
799
1992
  getTool(toolId) {
800
- return new Tool(this.options, toolId);
1993
+ return new Tool2(this.options, toolId);
1994
+ }
1995
+ /**
1996
+ * Retrieves all available legacy workflows
1997
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1998
+ */
1999
+ getLegacyWorkflows() {
2000
+ return this.request("/api/workflows/legacy");
2001
+ }
2002
+ /**
2003
+ * Gets a legacy workflow instance by ID
2004
+ * @param workflowId - ID of the legacy workflow to retrieve
2005
+ * @returns Legacy Workflow instance
2006
+ */
2007
+ getLegacyWorkflow(workflowId) {
2008
+ return new LegacyWorkflow(this.options, workflowId);
801
2009
  }
802
2010
  /**
803
2011
  * Retrieves all available workflows
@@ -814,21 +2022,6 @@ var MastraClient = class extends BaseResource {
814
2022
  getWorkflow(workflowId) {
815
2023
  return new Workflow(this.options, workflowId);
816
2024
  }
817
- /**
818
- * Retrieves all available vNext workflows
819
- * @returns Promise containing map of vNext workflow IDs to vNext workflow details
820
- */
821
- getVNextWorkflows() {
822
- return this.request("/api/workflows/v-next");
823
- }
824
- /**
825
- * Gets a vNext workflow instance by ID
826
- * @param workflowId - ID of the vNext workflow to retrieve
827
- * @returns vNext Workflow instance
828
- */
829
- getVNextWorkflow(workflowId) {
830
- return new VNextWorkflow(this.options, workflowId);
831
- }
832
2025
  /**
833
2026
  * Gets a vector instance by name
834
2027
  * @param vectorName - Name of the vector to retrieve
@@ -843,7 +2036,41 @@ var MastraClient = class extends BaseResource {
843
2036
  * @returns Promise containing array of log messages
844
2037
  */
845
2038
  getLogs(params) {
846
- return this.request(`/api/logs?transportId=${params.transportId}`);
2039
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2040
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2041
+ const searchParams = new URLSearchParams();
2042
+ if (transportId) {
2043
+ searchParams.set("transportId", transportId);
2044
+ }
2045
+ if (fromDate) {
2046
+ searchParams.set("fromDate", fromDate.toISOString());
2047
+ }
2048
+ if (toDate) {
2049
+ searchParams.set("toDate", toDate.toISOString());
2050
+ }
2051
+ if (logLevel) {
2052
+ searchParams.set("logLevel", logLevel);
2053
+ }
2054
+ if (page) {
2055
+ searchParams.set("page", String(page));
2056
+ }
2057
+ if (perPage) {
2058
+ searchParams.set("perPage", String(perPage));
2059
+ }
2060
+ if (_filters) {
2061
+ if (Array.isArray(_filters)) {
2062
+ for (const filter of _filters) {
2063
+ searchParams.append("filters", filter);
2064
+ }
2065
+ } else {
2066
+ searchParams.set("filters", _filters);
2067
+ }
2068
+ }
2069
+ if (searchParams.size) {
2070
+ return this.request(`/api/logs?${searchParams}`);
2071
+ } else {
2072
+ return this.request(`/api/logs`);
2073
+ }
847
2074
  }
848
2075
  /**
849
2076
  * Gets logs for a specific run
@@ -851,7 +2078,44 @@ var MastraClient = class extends BaseResource {
851
2078
  * @returns Promise containing array of log messages
852
2079
  */
853
2080
  getLogForRun(params) {
854
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2081
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2082
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2083
+ const searchParams = new URLSearchParams();
2084
+ if (runId) {
2085
+ searchParams.set("runId", runId);
2086
+ }
2087
+ if (transportId) {
2088
+ searchParams.set("transportId", transportId);
2089
+ }
2090
+ if (fromDate) {
2091
+ searchParams.set("fromDate", fromDate.toISOString());
2092
+ }
2093
+ if (toDate) {
2094
+ searchParams.set("toDate", toDate.toISOString());
2095
+ }
2096
+ if (logLevel) {
2097
+ searchParams.set("logLevel", logLevel);
2098
+ }
2099
+ if (page) {
2100
+ searchParams.set("page", String(page));
2101
+ }
2102
+ if (perPage) {
2103
+ searchParams.set("perPage", String(perPage));
2104
+ }
2105
+ if (_filters) {
2106
+ if (Array.isArray(_filters)) {
2107
+ for (const filter of _filters) {
2108
+ searchParams.append("filters", filter);
2109
+ }
2110
+ } else {
2111
+ searchParams.set("filters", _filters);
2112
+ }
2113
+ }
2114
+ if (searchParams.size) {
2115
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2116
+ } else {
2117
+ return this.request(`/api/logs/${runId}`);
2118
+ }
855
2119
  }
856
2120
  /**
857
2121
  * List of all log transports
@@ -866,7 +2130,7 @@ var MastraClient = class extends BaseResource {
866
2130
  * @returns Promise containing telemetry data
867
2131
  */
868
2132
  getTelemetry(params) {
869
- const { name, scope, page, perPage, attribute } = params || {};
2133
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
870
2134
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
871
2135
  const searchParams = new URLSearchParams();
872
2136
  if (name) {
@@ -890,6 +2154,12 @@ var MastraClient = class extends BaseResource {
890
2154
  searchParams.set("attribute", _attribute);
891
2155
  }
892
2156
  }
2157
+ if (fromDate) {
2158
+ searchParams.set("fromDate", fromDate.toISOString());
2159
+ }
2160
+ if (toDate) {
2161
+ searchParams.set("toDate", toDate.toISOString());
2162
+ }
893
2163
  if (searchParams.size) {
894
2164
  return this.request(`/api/telemetry?${searchParams}`);
895
2165
  } else {
@@ -903,6 +2173,13 @@ var MastraClient = class extends BaseResource {
903
2173
  getNetworks() {
904
2174
  return this.request("/api/networks");
905
2175
  }
2176
+ /**
2177
+ * Retrieves all available vNext networks
2178
+ * @returns Promise containing map of vNext network IDs to vNext network details
2179
+ */
2180
+ getVNextNetworks() {
2181
+ return this.request("/api/networks/v-next");
2182
+ }
906
2183
  /**
907
2184
  * Gets a network instance by ID
908
2185
  * @param networkId - ID of the network to retrieve
@@ -911,6 +2188,105 @@ var MastraClient = class extends BaseResource {
911
2188
  getNetwork(networkId) {
912
2189
  return new Network(this.options, networkId);
913
2190
  }
2191
+ /**
2192
+ * Gets a vNext network instance by ID
2193
+ * @param networkId - ID of the vNext network to retrieve
2194
+ * @returns vNext Network instance
2195
+ */
2196
+ getVNextNetwork(networkId) {
2197
+ return new VNextNetwork(this.options, networkId);
2198
+ }
2199
+ /**
2200
+ * Retrieves a list of available MCP servers.
2201
+ * @param params - Optional parameters for pagination (limit, offset).
2202
+ * @returns Promise containing the list of MCP servers and pagination info.
2203
+ */
2204
+ getMcpServers(params) {
2205
+ const searchParams = new URLSearchParams();
2206
+ if (params?.limit !== void 0) {
2207
+ searchParams.set("limit", String(params.limit));
2208
+ }
2209
+ if (params?.offset !== void 0) {
2210
+ searchParams.set("offset", String(params.offset));
2211
+ }
2212
+ const queryString = searchParams.toString();
2213
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2214
+ }
2215
+ /**
2216
+ * Retrieves detailed information for a specific MCP server.
2217
+ * @param serverId - The ID of the MCP server to retrieve.
2218
+ * @param params - Optional parameters, e.g., specific version.
2219
+ * @returns Promise containing the detailed MCP server information.
2220
+ */
2221
+ getMcpServerDetails(serverId, params) {
2222
+ const searchParams = new URLSearchParams();
2223
+ if (params?.version) {
2224
+ searchParams.set("version", params.version);
2225
+ }
2226
+ const queryString = searchParams.toString();
2227
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2228
+ }
2229
+ /**
2230
+ * Retrieves a list of tools for a specific MCP server.
2231
+ * @param serverId - The ID of the MCP server.
2232
+ * @returns Promise containing the list of tools.
2233
+ */
2234
+ getMcpServerTools(serverId) {
2235
+ return this.request(`/api/mcp/${serverId}/tools`);
2236
+ }
2237
+ /**
2238
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2239
+ * This instance can then be used to fetch details or execute the tool.
2240
+ * @param serverId - The ID of the MCP server.
2241
+ * @param toolId - The ID of the tool.
2242
+ * @returns MCPTool instance.
2243
+ */
2244
+ getMcpServerTool(serverId, toolId) {
2245
+ return new MCPTool(this.options, serverId, toolId);
2246
+ }
2247
+ /**
2248
+ * Gets an A2A client for interacting with an agent via the A2A protocol
2249
+ * @param agentId - ID of the agent to interact with
2250
+ * @returns A2A client instance
2251
+ */
2252
+ getA2A(agentId) {
2253
+ return new A2A(this.options, agentId);
2254
+ }
2255
+ /**
2256
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2257
+ * @param agentId - ID of the agent.
2258
+ * @param threadId - ID of the thread.
2259
+ * @param resourceId - Optional ID of the resource.
2260
+ * @returns Working memory for the specified thread or resource.
2261
+ */
2262
+ getWorkingMemory({
2263
+ agentId,
2264
+ threadId,
2265
+ resourceId
2266
+ }) {
2267
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2268
+ }
2269
+ /**
2270
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2271
+ * @param agentId - ID of the agent.
2272
+ * @param threadId - ID of the thread.
2273
+ * @param workingMemory - The new working memory content.
2274
+ * @param resourceId - Optional ID of the resource.
2275
+ */
2276
+ updateWorkingMemory({
2277
+ agentId,
2278
+ threadId,
2279
+ workingMemory,
2280
+ resourceId
2281
+ }) {
2282
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2283
+ method: "POST",
2284
+ body: {
2285
+ workingMemory,
2286
+ resourceId
2287
+ }
2288
+ });
2289
+ }
914
2290
  };
915
2291
 
916
2292
  export { MastraClient };