@mastra/client-js 0.0.0-expose-more-playground-ui-20250502141824 → 0.0.0-feat-tool-input-validation-20250731232758

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 { 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/is-vercel-tool';
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.body && !(options.body instanceof FormData) && (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,21 +363,325 @@ 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`, {
140
- method: "POST",
141
- body: processedParams
374
+ const { runId, resourceId, threadId, runtimeContext } = processedParams;
375
+ const response = await this.request(
376
+ `/api/agents/${this.agentId}/generate`,
377
+ {
378
+ method: "POST",
379
+ body: processedParams
380
+ }
381
+ );
382
+ if (response.finishReason === "tool-calls") {
383
+ const toolCalls = response.toolCalls;
384
+ if (!toolCalls || !Array.isArray(toolCalls)) {
385
+ return response;
386
+ }
387
+ for (const toolCall of toolCalls) {
388
+ const clientTool = params.clientTools?.[toolCall.toolName];
389
+ if (clientTool && clientTool.execute) {
390
+ const result = await clientTool.execute(
391
+ { context: toolCall?.args, runId, resourceId, threadId, runtimeContext },
392
+ {
393
+ messages: response.messages,
394
+ toolCallId: toolCall?.toolCallId
395
+ }
396
+ );
397
+ const updatedMessages = [
398
+ {
399
+ role: "user",
400
+ content: params.messages
401
+ },
402
+ ...response.response.messages,
403
+ {
404
+ role: "tool",
405
+ content: [
406
+ {
407
+ type: "tool-result",
408
+ toolCallId: toolCall.toolCallId,
409
+ toolName: toolCall.toolName,
410
+ result
411
+ }
412
+ ]
413
+ }
414
+ ];
415
+ return this.generate({
416
+ ...params,
417
+ messages: updatedMessages
418
+ });
419
+ }
420
+ }
421
+ }
422
+ return response;
423
+ }
424
+ async processChatResponse({
425
+ stream,
426
+ update,
427
+ onToolCall,
428
+ onFinish,
429
+ getCurrentDate = () => /* @__PURE__ */ new Date(),
430
+ lastMessage
431
+ }) {
432
+ const replaceLastMessage = lastMessage?.role === "assistant";
433
+ let step = replaceLastMessage ? 1 + // find max step in existing tool invocations:
434
+ (lastMessage.toolInvocations?.reduce((max, toolInvocation) => {
435
+ return Math.max(max, toolInvocation.step ?? 0);
436
+ }, 0) ?? 0) : 0;
437
+ const message = replaceLastMessage ? structuredClone(lastMessage) : {
438
+ id: v4(),
439
+ createdAt: getCurrentDate(),
440
+ role: "assistant",
441
+ content: "",
442
+ parts: []
443
+ };
444
+ let currentTextPart = void 0;
445
+ let currentReasoningPart = void 0;
446
+ let currentReasoningTextDetail = void 0;
447
+ function updateToolInvocationPart(toolCallId, invocation) {
448
+ const part = message.parts.find(
449
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
450
+ );
451
+ if (part != null) {
452
+ part.toolInvocation = invocation;
453
+ } else {
454
+ message.parts.push({
455
+ type: "tool-invocation",
456
+ toolInvocation: invocation
457
+ });
458
+ }
459
+ }
460
+ const data = [];
461
+ let messageAnnotations = replaceLastMessage ? lastMessage?.annotations : void 0;
462
+ const partialToolCalls = {};
463
+ let usage = {
464
+ completionTokens: NaN,
465
+ promptTokens: NaN,
466
+ totalTokens: NaN
467
+ };
468
+ let finishReason = "unknown";
469
+ function execUpdate() {
470
+ const copiedData = [...data];
471
+ if (messageAnnotations?.length) {
472
+ message.annotations = messageAnnotations;
473
+ }
474
+ const copiedMessage = {
475
+ // deep copy the message to ensure that deep changes (msg attachments) are updated
476
+ // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
477
+ ...structuredClone(message),
478
+ // add a revision id to ensure that the message is updated with SWR. SWR uses a
479
+ // hashing approach by default to detect changes, but it only works for shallow
480
+ // changes. This is why we need to add a revision id to ensure that the message
481
+ // is updated with SWR (without it, the changes get stuck in SWR and are not
482
+ // forwarded to rendering):
483
+ revisionId: v4()
484
+ };
485
+ update({
486
+ message: copiedMessage,
487
+ data: copiedData,
488
+ replaceLastMessage
489
+ });
490
+ }
491
+ await processDataStream({
492
+ stream,
493
+ onTextPart(value) {
494
+ if (currentTextPart == null) {
495
+ currentTextPart = {
496
+ type: "text",
497
+ text: value
498
+ };
499
+ message.parts.push(currentTextPart);
500
+ } else {
501
+ currentTextPart.text += value;
502
+ }
503
+ message.content += value;
504
+ execUpdate();
505
+ },
506
+ onReasoningPart(value) {
507
+ if (currentReasoningTextDetail == null) {
508
+ currentReasoningTextDetail = { type: "text", text: value };
509
+ if (currentReasoningPart != null) {
510
+ currentReasoningPart.details.push(currentReasoningTextDetail);
511
+ }
512
+ } else {
513
+ currentReasoningTextDetail.text += value;
514
+ }
515
+ if (currentReasoningPart == null) {
516
+ currentReasoningPart = {
517
+ type: "reasoning",
518
+ reasoning: value,
519
+ details: [currentReasoningTextDetail]
520
+ };
521
+ message.parts.push(currentReasoningPart);
522
+ } else {
523
+ currentReasoningPart.reasoning += value;
524
+ }
525
+ message.reasoning = (message.reasoning ?? "") + value;
526
+ execUpdate();
527
+ },
528
+ onReasoningSignaturePart(value) {
529
+ if (currentReasoningTextDetail != null) {
530
+ currentReasoningTextDetail.signature = value.signature;
531
+ }
532
+ },
533
+ onRedactedReasoningPart(value) {
534
+ if (currentReasoningPart == null) {
535
+ currentReasoningPart = {
536
+ type: "reasoning",
537
+ reasoning: "",
538
+ details: []
539
+ };
540
+ message.parts.push(currentReasoningPart);
541
+ }
542
+ currentReasoningPart.details.push({
543
+ type: "redacted",
544
+ data: value.data
545
+ });
546
+ currentReasoningTextDetail = void 0;
547
+ execUpdate();
548
+ },
549
+ onFilePart(value) {
550
+ message.parts.push({
551
+ type: "file",
552
+ mimeType: value.mimeType,
553
+ data: value.data
554
+ });
555
+ execUpdate();
556
+ },
557
+ onSourcePart(value) {
558
+ message.parts.push({
559
+ type: "source",
560
+ source: value
561
+ });
562
+ execUpdate();
563
+ },
564
+ onToolCallStreamingStartPart(value) {
565
+ if (message.toolInvocations == null) {
566
+ message.toolInvocations = [];
567
+ }
568
+ partialToolCalls[value.toolCallId] = {
569
+ text: "",
570
+ step,
571
+ toolName: value.toolName,
572
+ index: message.toolInvocations.length
573
+ };
574
+ const invocation = {
575
+ state: "partial-call",
576
+ step,
577
+ toolCallId: value.toolCallId,
578
+ toolName: value.toolName,
579
+ args: void 0
580
+ };
581
+ message.toolInvocations.push(invocation);
582
+ updateToolInvocationPart(value.toolCallId, invocation);
583
+ execUpdate();
584
+ },
585
+ onToolCallDeltaPart(value) {
586
+ const partialToolCall = partialToolCalls[value.toolCallId];
587
+ partialToolCall.text += value.argsTextDelta;
588
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
589
+ const invocation = {
590
+ state: "partial-call",
591
+ step: partialToolCall.step,
592
+ toolCallId: value.toolCallId,
593
+ toolName: partialToolCall.toolName,
594
+ args: partialArgs
595
+ };
596
+ message.toolInvocations[partialToolCall.index] = invocation;
597
+ updateToolInvocationPart(value.toolCallId, invocation);
598
+ execUpdate();
599
+ },
600
+ async onToolCallPart(value) {
601
+ const invocation = {
602
+ state: "call",
603
+ step,
604
+ ...value
605
+ };
606
+ if (partialToolCalls[value.toolCallId] != null) {
607
+ message.toolInvocations[partialToolCalls[value.toolCallId].index] = invocation;
608
+ } else {
609
+ if (message.toolInvocations == null) {
610
+ message.toolInvocations = [];
611
+ }
612
+ message.toolInvocations.push(invocation);
613
+ }
614
+ updateToolInvocationPart(value.toolCallId, invocation);
615
+ execUpdate();
616
+ if (onToolCall) {
617
+ const result = await onToolCall({ toolCall: value });
618
+ if (result != null) {
619
+ const invocation2 = {
620
+ state: "result",
621
+ step,
622
+ ...value,
623
+ result
624
+ };
625
+ message.toolInvocations[message.toolInvocations.length - 1] = invocation2;
626
+ updateToolInvocationPart(value.toolCallId, invocation2);
627
+ execUpdate();
628
+ }
629
+ }
630
+ },
631
+ onToolResultPart(value) {
632
+ const toolInvocations = message.toolInvocations;
633
+ if (toolInvocations == null) {
634
+ throw new Error("tool_result must be preceded by a tool_call");
635
+ }
636
+ const toolInvocationIndex = toolInvocations.findIndex((invocation2) => invocation2.toolCallId === value.toolCallId);
637
+ if (toolInvocationIndex === -1) {
638
+ throw new Error("tool_result must be preceded by a tool_call with the same toolCallId");
639
+ }
640
+ const invocation = {
641
+ ...toolInvocations[toolInvocationIndex],
642
+ state: "result",
643
+ ...value
644
+ };
645
+ toolInvocations[toolInvocationIndex] = invocation;
646
+ updateToolInvocationPart(value.toolCallId, invocation);
647
+ execUpdate();
648
+ },
649
+ onDataPart(value) {
650
+ data.push(...value);
651
+ execUpdate();
652
+ },
653
+ onMessageAnnotationsPart(value) {
654
+ if (messageAnnotations == null) {
655
+ messageAnnotations = [...value];
656
+ } else {
657
+ messageAnnotations.push(...value);
658
+ }
659
+ execUpdate();
660
+ },
661
+ onFinishStepPart(value) {
662
+ step += 1;
663
+ currentTextPart = value.isContinued ? currentTextPart : void 0;
664
+ currentReasoningPart = void 0;
665
+ currentReasoningTextDetail = void 0;
666
+ },
667
+ onStartStepPart(value) {
668
+ if (!replaceLastMessage) {
669
+ message.id = value.messageId;
670
+ }
671
+ message.parts.push({ type: "step-start" });
672
+ execUpdate();
673
+ },
674
+ onFinishMessagePart(value) {
675
+ finishReason = value.finishReason;
676
+ if (value.usage != null) {
677
+ usage = value.usage;
678
+ }
679
+ },
680
+ onErrorPart(error) {
681
+ throw new Error(error);
682
+ }
142
683
  });
684
+ onFinish?.({ message, finishReason, usage });
143
685
  }
144
686
  /**
145
687
  * Streams a response from the agent
@@ -149,9 +691,30 @@ var Agent = class extends BaseResource {
149
691
  async stream(params) {
150
692
  const processedParams = {
151
693
  ...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
694
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
695
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
696
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
697
+ clientTools: processClientTools(params.clientTools)
698
+ };
699
+ const { readable, writable } = new TransformStream();
700
+ const response = await this.processStreamResponse(processedParams, writable);
701
+ const streamResponse = new Response(readable, {
702
+ status: response.status,
703
+ statusText: response.statusText,
704
+ headers: response.headers
705
+ });
706
+ streamResponse.processDataStream = async (options = {}) => {
707
+ await processDataStream({
708
+ stream: streamResponse.body,
709
+ ...options
710
+ });
154
711
  };
712
+ return streamResponse;
713
+ }
714
+ /**
715
+ * Processes the stream response and handles tool calls
716
+ */
717
+ async processStreamResponse(processedParams, writable) {
155
718
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
156
719
  method: "POST",
157
720
  body: processedParams,
@@ -160,12 +723,104 @@ var Agent = class extends BaseResource {
160
723
  if (!response.body) {
161
724
  throw new Error("No response body");
162
725
  }
163
- response.processDataStream = async (options = {}) => {
164
- await processDataStream({
165
- stream: response.body,
166
- ...options
726
+ try {
727
+ let toolCalls = [];
728
+ let messages = [];
729
+ const [streamForWritable, streamForProcessing] = response.body.tee();
730
+ streamForWritable.pipeTo(writable, {
731
+ preventClose: true
732
+ }).catch((error) => {
733
+ console.error("Error piping to writable stream:", error);
167
734
  });
168
- };
735
+ this.processChatResponse({
736
+ stream: streamForProcessing,
737
+ update: ({ message }) => {
738
+ const existingIndex = messages.findIndex((m) => m.id === message.id);
739
+ if (existingIndex !== -1) {
740
+ messages[existingIndex] = message;
741
+ } else {
742
+ messages.push(message);
743
+ }
744
+ },
745
+ onFinish: async ({ finishReason, message }) => {
746
+ if (finishReason === "tool-calls") {
747
+ const toolCall = [...message?.parts ?? []].reverse().find((part) => part.type === "tool-invocation")?.toolInvocation;
748
+ if (toolCall) {
749
+ toolCalls.push(toolCall);
750
+ }
751
+ for (const toolCall2 of toolCalls) {
752
+ const clientTool = processedParams.clientTools?.[toolCall2.toolName];
753
+ if (clientTool && clientTool.execute) {
754
+ const result = await clientTool.execute(
755
+ {
756
+ context: toolCall2?.args,
757
+ runId: processedParams.runId,
758
+ resourceId: processedParams.resourceId,
759
+ threadId: processedParams.threadId,
760
+ runtimeContext: processedParams.runtimeContext
761
+ },
762
+ {
763
+ messages: response.messages,
764
+ toolCallId: toolCall2?.toolCallId
765
+ }
766
+ );
767
+ const lastMessage = JSON.parse(JSON.stringify(messages[messages.length - 1]));
768
+ const toolInvocationPart = lastMessage?.parts?.find(
769
+ (part) => part.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCall2.toolCallId
770
+ );
771
+ if (toolInvocationPart) {
772
+ toolInvocationPart.toolInvocation = {
773
+ ...toolInvocationPart.toolInvocation,
774
+ state: "result",
775
+ result
776
+ };
777
+ }
778
+ const toolInvocation = lastMessage?.toolInvocations?.find(
779
+ (toolInvocation2) => toolInvocation2.toolCallId === toolCall2.toolCallId
780
+ );
781
+ if (toolInvocation) {
782
+ toolInvocation.state = "result";
783
+ toolInvocation.result = result;
784
+ }
785
+ const writer = writable.getWriter();
786
+ try {
787
+ await writer.write(
788
+ new TextEncoder().encode(
789
+ "a:" + JSON.stringify({
790
+ toolCallId: toolCall2.toolCallId,
791
+ result
792
+ }) + "\n"
793
+ )
794
+ );
795
+ } finally {
796
+ writer.releaseLock();
797
+ }
798
+ const originalMessages = processedParams.messages;
799
+ const messageArray = Array.isArray(originalMessages) ? originalMessages : [originalMessages];
800
+ this.processStreamResponse(
801
+ {
802
+ ...processedParams,
803
+ messages: [...messageArray, ...messages.filter((m) => m.id !== lastMessage.id), lastMessage]
804
+ },
805
+ writable
806
+ ).catch((error) => {
807
+ console.error("Error processing stream response:", error);
808
+ });
809
+ }
810
+ }
811
+ } else {
812
+ setTimeout(() => {
813
+ writable.close();
814
+ }, 0);
815
+ }
816
+ },
817
+ lastMessage: void 0
818
+ }).catch((error) => {
819
+ console.error("Error processing stream response:", error);
820
+ });
821
+ } catch (error) {
822
+ console.error("Error processing stream response:", error);
823
+ }
169
824
  return response;
170
825
  }
171
826
  /**
@@ -176,6 +831,22 @@ var Agent = class extends BaseResource {
176
831
  getTool(toolId) {
177
832
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
178
833
  }
834
+ /**
835
+ * Executes a tool for the agent
836
+ * @param toolId - ID of the tool to execute
837
+ * @param params - Parameters required for tool execution
838
+ * @returns Promise containing the tool execution results
839
+ */
840
+ executeTool(toolId, params) {
841
+ const body = {
842
+ data: params.data,
843
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
844
+ };
845
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
846
+ method: "POST",
847
+ body
848
+ });
849
+ }
179
850
  /**
180
851
  * Retrieves evaluation results for the agent
181
852
  * @returns Promise containing agent evaluations
@@ -211,8 +882,8 @@ var Network = class extends BaseResource {
211
882
  generate(params) {
212
883
  const processedParams = {
213
884
  ...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
885
+ output: zodToJsonSchema(params.output),
886
+ experimental_output: zodToJsonSchema(params.experimental_output)
216
887
  };
217
888
  return this.request(`/api/networks/${this.networkId}/generate`, {
218
889
  method: "POST",
@@ -227,8 +898,8 @@ var Network = class extends BaseResource {
227
898
  async stream(params) {
228
899
  const processedParams = {
229
900
  ...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
901
+ output: zodToJsonSchema(params.output),
902
+ experimental_output: zodToJsonSchema(params.experimental_output)
232
903
  };
233
904
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
234
905
  method: "POST",
@@ -284,10 +955,45 @@ var MemoryThread = class extends BaseResource {
284
955
  }
285
956
  /**
286
957
  * Retrieves messages associated with the thread
958
+ * @param params - Optional parameters including limit for number of messages to retrieve
287
959
  * @returns Promise containing thread messages and UI messages
288
960
  */
289
- getMessages() {
290
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
961
+ getMessages(params) {
962
+ const query = new URLSearchParams({
963
+ agentId: this.agentId,
964
+ ...params?.limit ? { limit: params.limit.toString() } : {}
965
+ });
966
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
967
+ }
968
+ /**
969
+ * Retrieves paginated messages associated with the thread with advanced filtering and selection options
970
+ * @param params - Pagination parameters including selectBy criteria, page, perPage, date ranges, and message inclusion options
971
+ * @returns Promise containing paginated thread messages with pagination metadata (total, page, perPage, hasMore)
972
+ */
973
+ getMessagesPaginated({
974
+ selectBy,
975
+ ...rest
976
+ }) {
977
+ const query = new URLSearchParams({
978
+ ...rest,
979
+ ...selectBy ? { selectBy: JSON.stringify(selectBy) } : {}
980
+ });
981
+ return this.request(`/api/memory/threads/${this.threadId}/messages/paginated?${query.toString()}`);
982
+ }
983
+ /**
984
+ * Deletes one or more messages from the thread
985
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
986
+ * message object with id property, or array of message objects
987
+ * @returns Promise containing deletion result
988
+ */
989
+ deleteMessages(messageIds) {
990
+ const query = new URLSearchParams({
991
+ agentId: this.agentId
992
+ });
993
+ return this.request(`/api/memory/messages/delete?${query.toString()}`, {
994
+ method: "POST",
995
+ body: { messageIds }
996
+ });
291
997
  }
292
998
  };
293
999
 
@@ -357,41 +1063,50 @@ var Vector = class extends BaseResource {
357
1063
  }
358
1064
  };
359
1065
 
360
- // src/resources/workflow.ts
1066
+ // src/resources/legacy-workflow.ts
361
1067
  var RECORD_SEPARATOR = "";
362
- var Workflow = class extends BaseResource {
1068
+ var LegacyWorkflow = class extends BaseResource {
363
1069
  constructor(options, workflowId) {
364
1070
  super(options);
365
1071
  this.workflowId = workflowId;
366
1072
  }
367
1073
  /**
368
- * Retrieves details about the workflow
369
- * @returns Promise containing workflow details including steps and graphs
1074
+ * Retrieves details about the legacy workflow
1075
+ * @returns Promise containing legacy workflow details including steps and graphs
370
1076
  */
371
1077
  details() {
372
- return this.request(`/api/workflows/${this.workflowId}`);
1078
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
373
1079
  }
374
1080
  /**
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
1081
+ * Retrieves all runs for a legacy workflow
1082
+ * @param params - Parameters for filtering runs
1083
+ * @returns Promise containing legacy workflow runs array
386
1084
  */
387
- execute(params) {
388
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
389
- method: "POST",
390
- body: params
391
- });
1085
+ runs(params) {
1086
+ const searchParams = new URLSearchParams();
1087
+ if (params?.fromDate) {
1088
+ searchParams.set("fromDate", params.fromDate.toISOString());
1089
+ }
1090
+ if (params?.toDate) {
1091
+ searchParams.set("toDate", params.toDate.toISOString());
1092
+ }
1093
+ if (params?.limit) {
1094
+ searchParams.set("limit", String(params.limit));
1095
+ }
1096
+ if (params?.offset) {
1097
+ searchParams.set("offset", String(params.offset));
1098
+ }
1099
+ if (params?.resourceId) {
1100
+ searchParams.set("resourceId", params.resourceId);
1101
+ }
1102
+ if (searchParams.size) {
1103
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
1104
+ } else {
1105
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
1106
+ }
392
1107
  }
393
1108
  /**
394
- * Creates a new workflow run
1109
+ * Creates a new legacy workflow run
395
1110
  * @returns Promise containing the generated run ID
396
1111
  */
397
1112
  createRun(params) {
@@ -399,34 +1114,34 @@ var Workflow = class extends BaseResource {
399
1114
  if (!!params?.runId) {
400
1115
  searchParams.set("runId", params.runId);
401
1116
  }
402
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
1117
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
403
1118
  method: "POST"
404
1119
  });
405
1120
  }
406
1121
  /**
407
- * Starts a workflow run synchronously without waiting for the workflow to complete
1122
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
408
1123
  * @param params - Object containing the runId and triggerData
409
1124
  * @returns Promise containing success message
410
1125
  */
411
1126
  start(params) {
412
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
1127
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
413
1128
  method: "POST",
414
1129
  body: params?.triggerData
415
1130
  });
416
1131
  }
417
1132
  /**
418
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
1133
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
419
1134
  * @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
1135
+ * @param runId - ID of the legacy workflow run
1136
+ * @param context - Context to resume the legacy workflow with
1137
+ * @returns Promise containing the legacy workflow resume results
423
1138
  */
424
1139
  resume({
425
1140
  stepId,
426
1141
  runId,
427
1142
  context
428
1143
  }) {
429
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
1144
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
430
1145
  method: "POST",
431
1146
  body: {
432
1147
  stepId,
@@ -444,18 +1159,18 @@ var Workflow = class extends BaseResource {
444
1159
  if (!!params?.runId) {
445
1160
  searchParams.set("runId", params.runId);
446
1161
  }
447
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1162
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
448
1163
  method: "POST",
449
1164
  body: params?.triggerData
450
1165
  });
451
1166
  }
452
1167
  /**
453
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1168
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
454
1169
  * @param params - Object containing the runId, stepId, and context
455
1170
  * @returns Promise containing the workflow resume results
456
1171
  */
457
1172
  resumeAsync(params) {
458
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1173
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
459
1174
  method: "POST",
460
1175
  body: {
461
1176
  stepId: params.stepId,
@@ -509,16 +1224,16 @@ var Workflow = class extends BaseResource {
509
1224
  }
510
1225
  }
511
1226
  /**
512
- * Watches workflow transitions in real-time
1227
+ * Watches legacy workflow transitions in real-time
513
1228
  * @param runId - Optional run ID to filter the watch stream
514
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1229
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
515
1230
  */
516
1231
  async watch({ runId }, onRecord) {
517
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1232
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
518
1233
  stream: true
519
1234
  });
520
1235
  if (!response.ok) {
521
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
1236
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
522
1237
  }
523
1238
  if (!response.body) {
524
1239
  throw new Error("Response body is null");
@@ -530,7 +1245,7 @@ var Workflow = class extends BaseResource {
530
1245
  };
531
1246
 
532
1247
  // src/resources/tool.ts
533
- var Tool = class extends BaseResource {
1248
+ var Tool2 = class extends BaseResource {
534
1249
  constructor(options, toolId) {
535
1250
  super(options);
536
1251
  this.toolId = toolId;
@@ -552,22 +1267,26 @@ var Tool = class extends BaseResource {
552
1267
  if (params.runId) {
553
1268
  url.set("runId", params.runId);
554
1269
  }
1270
+ const body = {
1271
+ data: params.data,
1272
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1273
+ };
555
1274
  return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
556
1275
  method: "POST",
557
- body: params.data
1276
+ body
558
1277
  });
559
1278
  }
560
1279
  };
561
1280
 
562
- // src/resources/vnext-workflow.ts
1281
+ // src/resources/workflow.ts
563
1282
  var RECORD_SEPARATOR2 = "";
564
- var VNextWorkflow = class extends BaseResource {
1283
+ var Workflow = class extends BaseResource {
565
1284
  constructor(options, workflowId) {
566
1285
  super(options);
567
1286
  this.workflowId = workflowId;
568
1287
  }
569
1288
  /**
570
- * Creates an async generator that processes a readable stream and yields vNext workflow records
1289
+ * Creates an async generator that processes a readable stream and yields workflow records
571
1290
  * separated by the Record Separator character (\x1E)
572
1291
  *
573
1292
  * @param stream - The readable stream to process
@@ -612,21 +1331,79 @@ var VNextWorkflow = class extends BaseResource {
612
1331
  }
613
1332
  }
614
1333
  /**
615
- * Retrieves details about the vNext workflow
616
- * @returns Promise containing vNext workflow details including steps and graphs
1334
+ * Retrieves details about the workflow
1335
+ * @returns Promise containing workflow details including steps and graphs
617
1336
  */
618
1337
  details() {
619
- return this.request(`/api/workflows/v-next/${this.workflowId}`);
1338
+ return this.request(`/api/workflows/${this.workflowId}`);
1339
+ }
1340
+ /**
1341
+ * Retrieves all runs for a workflow
1342
+ * @param params - Parameters for filtering runs
1343
+ * @returns Promise containing workflow runs array
1344
+ */
1345
+ runs(params) {
1346
+ const searchParams = new URLSearchParams();
1347
+ if (params?.fromDate) {
1348
+ searchParams.set("fromDate", params.fromDate.toISOString());
1349
+ }
1350
+ if (params?.toDate) {
1351
+ searchParams.set("toDate", params.toDate.toISOString());
1352
+ }
1353
+ if (params?.limit !== null && params?.limit !== void 0 && !isNaN(Number(params?.limit))) {
1354
+ searchParams.set("limit", String(params.limit));
1355
+ }
1356
+ if (params?.offset !== null && params?.offset !== void 0 && !isNaN(Number(params?.offset))) {
1357
+ searchParams.set("offset", String(params.offset));
1358
+ }
1359
+ if (params?.resourceId) {
1360
+ searchParams.set("resourceId", params.resourceId);
1361
+ }
1362
+ if (searchParams.size) {
1363
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
1364
+ } else {
1365
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Retrieves a specific workflow run by its ID
1370
+ * @param runId - The ID of the workflow run to retrieve
1371
+ * @returns Promise containing the workflow run details
1372
+ */
1373
+ runById(runId) {
1374
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
1375
+ }
1376
+ /**
1377
+ * Retrieves the execution result for a specific workflow run by its ID
1378
+ * @param runId - The ID of the workflow run to retrieve the execution result for
1379
+ * @returns Promise containing the workflow run execution result
1380
+ */
1381
+ runExecutionResult(runId) {
1382
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
1383
+ }
1384
+ /**
1385
+ * Cancels a specific workflow run by its ID
1386
+ * @param runId - The ID of the workflow run to cancel
1387
+ * @returns Promise containing a success message
1388
+ */
1389
+ cancelRun(runId) {
1390
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/cancel`, {
1391
+ method: "POST"
1392
+ });
620
1393
  }
621
1394
  /**
622
- * Retrieves all runs for a vNext workflow
623
- * @returns Promise containing vNext workflow runs array
1395
+ * Sends an event to a specific workflow run by its ID
1396
+ * @param params - Object containing the runId, event and data
1397
+ * @returns Promise containing a success message
624
1398
  */
625
- runs() {
626
- return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
1399
+ sendRunEvent(params) {
1400
+ return this.request(`/api/workflows/${this.workflowId}/runs/${params.runId}/send-event`, {
1401
+ method: "POST",
1402
+ body: { event: params.event, data: params.data }
1403
+ });
627
1404
  }
628
1405
  /**
629
- * Creates a new vNext workflow run
1406
+ * Creates a new workflow run
630
1407
  * @param params - Optional object containing the optional runId
631
1408
  * @returns Promise containing the runId of the created run
632
1409
  */
@@ -635,23 +1412,32 @@ var VNextWorkflow = class extends BaseResource {
635
1412
  if (!!params?.runId) {
636
1413
  searchParams.set("runId", params.runId);
637
1414
  }
638
- return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
1415
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
639
1416
  method: "POST"
640
1417
  });
641
1418
  }
642
1419
  /**
643
- * Starts a vNext workflow run synchronously without waiting for the workflow to complete
1420
+ * Creates a new workflow run (alias for createRun)
1421
+ * @param params - Optional object containing the optional runId
1422
+ * @returns Promise containing the runId of the created run
1423
+ */
1424
+ createRunAsync(params) {
1425
+ return this.createRun(params);
1426
+ }
1427
+ /**
1428
+ * Starts a workflow run synchronously without waiting for the workflow to complete
644
1429
  * @param params - Object containing the runId, inputData and runtimeContext
645
1430
  * @returns Promise containing success message
646
1431
  */
647
1432
  start(params) {
648
- return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
1433
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1434
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
649
1435
  method: "POST",
650
- body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
1436
+ body: { inputData: params?.inputData, runtimeContext }
651
1437
  });
652
1438
  }
653
1439
  /**
654
- * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
1440
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
655
1441
  * @param params - Object containing the runId, step, resumeData and runtimeContext
656
1442
  * @returns Promise containing success message
657
1443
  */
@@ -659,9 +1445,10 @@ var VNextWorkflow = class extends BaseResource {
659
1445
  step,
660
1446
  runId,
661
1447
  resumeData,
662
- runtimeContext
1448
+ ...rest
663
1449
  }) {
664
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
1450
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
1451
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
665
1452
  method: "POST",
666
1453
  stream: true,
667
1454
  body: {
@@ -672,55 +1459,444 @@ var VNextWorkflow = class extends BaseResource {
672
1459
  });
673
1460
  }
674
1461
  /**
675
- * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
1462
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
676
1463
  * @param params - Object containing the optional runId, inputData and runtimeContext
677
- * @returns Promise containing the vNext workflow execution results
1464
+ * @returns Promise containing the workflow execution results
678
1465
  */
679
1466
  startAsync(params) {
680
1467
  const searchParams = new URLSearchParams();
681
1468
  if (!!params?.runId) {
682
1469
  searchParams.set("runId", params.runId);
683
1470
  }
684
- return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
1471
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1472
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
685
1473
  method: "POST",
686
- body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
1474
+ body: { inputData: params.inputData, runtimeContext }
687
1475
  });
688
1476
  }
689
1477
  /**
690
- * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
691
- * @param params - Object containing the runId, step, resumeData and runtimeContext
692
- * @returns Promise containing the vNext workflow resume results
1478
+ * Starts a workflow run and returns a stream
1479
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1480
+ * @returns Promise containing the workflow execution results
693
1481
  */
694
- resumeAsync(params) {
695
- return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
696
- method: "POST",
697
- body: {
698
- step: params.step,
699
- resumeData: params.resumeData,
700
- runtimeContext: params.runtimeContext
1482
+ async stream(params) {
1483
+ const searchParams = new URLSearchParams();
1484
+ if (!!params?.runId) {
1485
+ searchParams.set("runId", params.runId);
1486
+ }
1487
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1488
+ const response = await this.request(
1489
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1490
+ {
1491
+ method: "POST",
1492
+ body: { inputData: params.inputData, runtimeContext },
1493
+ stream: true
701
1494
  }
702
- });
703
- }
704
- /**
705
- * Watches vNext workflow transitions in real-time
706
- * @param runId - Optional run ID to filter the watch stream
707
- * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
708
- */
709
- async watch({ runId }, onRecord) {
710
- const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
711
- stream: true
712
- });
1495
+ );
713
1496
  if (!response.ok) {
714
- throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
1497
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
715
1498
  }
716
1499
  if (!response.body) {
717
1500
  throw new Error("Response body is null");
718
1501
  }
719
- for await (const record of this.streamProcessor(response.body)) {
720
- onRecord(record);
721
- }
722
- }
723
- };
1502
+ let failedChunk = void 0;
1503
+ const transformStream = new TransformStream({
1504
+ start() {
1505
+ },
1506
+ async transform(chunk, controller) {
1507
+ try {
1508
+ const decoded = new TextDecoder().decode(chunk);
1509
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1510
+ for (const chunk2 of chunks) {
1511
+ if (chunk2) {
1512
+ const newChunk = failedChunk ? failedChunk + chunk2 : chunk2;
1513
+ try {
1514
+ const parsedChunk = JSON.parse(newChunk);
1515
+ controller.enqueue(parsedChunk);
1516
+ failedChunk = void 0;
1517
+ } catch (error) {
1518
+ failedChunk = newChunk;
1519
+ }
1520
+ }
1521
+ }
1522
+ } catch {
1523
+ }
1524
+ }
1525
+ });
1526
+ return response.body.pipeThrough(transformStream);
1527
+ }
1528
+ /**
1529
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1530
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1531
+ * @returns Promise containing the workflow resume results
1532
+ */
1533
+ resumeAsync(params) {
1534
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1535
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1536
+ method: "POST",
1537
+ body: {
1538
+ step: params.step,
1539
+ resumeData: params.resumeData,
1540
+ runtimeContext
1541
+ }
1542
+ });
1543
+ }
1544
+ /**
1545
+ * Watches workflow transitions in real-time
1546
+ * @param runId - Optional run ID to filter the watch stream
1547
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1548
+ */
1549
+ async watch({ runId }, onRecord) {
1550
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1551
+ stream: true
1552
+ });
1553
+ if (!response.ok) {
1554
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1555
+ }
1556
+ if (!response.body) {
1557
+ throw new Error("Response body is null");
1558
+ }
1559
+ for await (const record of this.streamProcessor(response.body)) {
1560
+ if (typeof record === "string") {
1561
+ onRecord(JSON.parse(record));
1562
+ } else {
1563
+ onRecord(record);
1564
+ }
1565
+ }
1566
+ }
1567
+ /**
1568
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1569
+ * serializing each as JSON and separating them with the record separator (\x1E).
1570
+ *
1571
+ * @param records - An iterable or async iterable of objects to stream
1572
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1573
+ */
1574
+ static createRecordStream(records) {
1575
+ const encoder = new TextEncoder();
1576
+ return new ReadableStream({
1577
+ async start(controller) {
1578
+ try {
1579
+ for await (const record of records) {
1580
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1581
+ controller.enqueue(encoder.encode(json));
1582
+ }
1583
+ controller.close();
1584
+ } catch (err) {
1585
+ controller.error(err);
1586
+ }
1587
+ }
1588
+ });
1589
+ }
1590
+ };
1591
+
1592
+ // src/resources/a2a.ts
1593
+ var A2A = class extends BaseResource {
1594
+ constructor(options, agentId) {
1595
+ super(options);
1596
+ this.agentId = agentId;
1597
+ }
1598
+ /**
1599
+ * Get the agent card with metadata about the agent
1600
+ * @returns Promise containing the agent card information
1601
+ */
1602
+ async getCard() {
1603
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1604
+ }
1605
+ /**
1606
+ * Send a message to the agent and get a response
1607
+ * @param params - Parameters for the task
1608
+ * @returns Promise containing the task response
1609
+ */
1610
+ async sendMessage(params) {
1611
+ const response = await this.request(`/a2a/${this.agentId}`, {
1612
+ method: "POST",
1613
+ body: {
1614
+ method: "tasks/send",
1615
+ params
1616
+ }
1617
+ });
1618
+ return { task: response.result };
1619
+ }
1620
+ /**
1621
+ * Get the status and result of a task
1622
+ * @param params - Parameters for querying the task
1623
+ * @returns Promise containing the task response
1624
+ */
1625
+ async getTask(params) {
1626
+ const response = await this.request(`/a2a/${this.agentId}`, {
1627
+ method: "POST",
1628
+ body: {
1629
+ method: "tasks/get",
1630
+ params
1631
+ }
1632
+ });
1633
+ return response.result;
1634
+ }
1635
+ /**
1636
+ * Cancel a running task
1637
+ * @param params - Parameters identifying the task to cancel
1638
+ * @returns Promise containing the task response
1639
+ */
1640
+ async cancelTask(params) {
1641
+ return this.request(`/a2a/${this.agentId}`, {
1642
+ method: "POST",
1643
+ body: {
1644
+ method: "tasks/cancel",
1645
+ params
1646
+ }
1647
+ });
1648
+ }
1649
+ /**
1650
+ * Send a message and subscribe to streaming updates (not fully implemented)
1651
+ * @param params - Parameters for the task
1652
+ * @returns Promise containing the task response
1653
+ */
1654
+ async sendAndSubscribe(params) {
1655
+ return this.request(`/a2a/${this.agentId}`, {
1656
+ method: "POST",
1657
+ body: {
1658
+ method: "tasks/sendSubscribe",
1659
+ params
1660
+ },
1661
+ stream: true
1662
+ });
1663
+ }
1664
+ };
1665
+
1666
+ // src/resources/mcp-tool.ts
1667
+ var MCPTool = class extends BaseResource {
1668
+ serverId;
1669
+ toolId;
1670
+ constructor(options, serverId, toolId) {
1671
+ super(options);
1672
+ this.serverId = serverId;
1673
+ this.toolId = toolId;
1674
+ }
1675
+ /**
1676
+ * Retrieves details about this specific tool from the MCP server.
1677
+ * @returns Promise containing the tool's information (name, description, schema).
1678
+ */
1679
+ details() {
1680
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1681
+ }
1682
+ /**
1683
+ * Executes this specific tool on the MCP server.
1684
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1685
+ * @returns Promise containing the result of the tool execution.
1686
+ */
1687
+ execute(params) {
1688
+ const body = {};
1689
+ if (params.data !== void 0) body.data = params.data;
1690
+ if (params.runtimeContext !== void 0) {
1691
+ body.runtimeContext = params.runtimeContext;
1692
+ }
1693
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1694
+ method: "POST",
1695
+ body: Object.keys(body).length > 0 ? body : void 0
1696
+ });
1697
+ }
1698
+ };
1699
+
1700
+ // src/resources/network-memory-thread.ts
1701
+ var NetworkMemoryThread = class extends BaseResource {
1702
+ constructor(options, threadId, networkId) {
1703
+ super(options);
1704
+ this.threadId = threadId;
1705
+ this.networkId = networkId;
1706
+ }
1707
+ /**
1708
+ * Retrieves the memory thread details
1709
+ * @returns Promise containing thread details including title and metadata
1710
+ */
1711
+ get() {
1712
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`);
1713
+ }
1714
+ /**
1715
+ * Updates the memory thread properties
1716
+ * @param params - Update parameters including title and metadata
1717
+ * @returns Promise containing updated thread details
1718
+ */
1719
+ update(params) {
1720
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1721
+ method: "PATCH",
1722
+ body: params
1723
+ });
1724
+ }
1725
+ /**
1726
+ * Deletes the memory thread
1727
+ * @returns Promise containing deletion result
1728
+ */
1729
+ delete() {
1730
+ return this.request(`/api/memory/network/threads/${this.threadId}?networkId=${this.networkId}`, {
1731
+ method: "DELETE"
1732
+ });
1733
+ }
1734
+ /**
1735
+ * Retrieves messages associated with the thread
1736
+ * @param params - Optional parameters including limit for number of messages to retrieve
1737
+ * @returns Promise containing thread messages and UI messages
1738
+ */
1739
+ getMessages(params) {
1740
+ const query = new URLSearchParams({
1741
+ networkId: this.networkId,
1742
+ ...params?.limit ? { limit: params.limit.toString() } : {}
1743
+ });
1744
+ return this.request(`/api/memory/network/threads/${this.threadId}/messages?${query.toString()}`);
1745
+ }
1746
+ /**
1747
+ * Deletes one or more messages from the thread
1748
+ * @param messageIds - Can be a single message ID (string), array of message IDs,
1749
+ * message object with id property, or array of message objects
1750
+ * @returns Promise containing deletion result
1751
+ */
1752
+ deleteMessages(messageIds) {
1753
+ const query = new URLSearchParams({
1754
+ networkId: this.networkId
1755
+ });
1756
+ return this.request(`/api/memory/network/messages/delete?${query.toString()}`, {
1757
+ method: "POST",
1758
+ body: { messageIds }
1759
+ });
1760
+ }
1761
+ };
1762
+
1763
+ // src/resources/vNextNetwork.ts
1764
+ var RECORD_SEPARATOR3 = "";
1765
+ var VNextNetwork = class extends BaseResource {
1766
+ constructor(options, networkId) {
1767
+ super(options);
1768
+ this.networkId = networkId;
1769
+ }
1770
+ /**
1771
+ * Retrieves details about the network
1772
+ * @returns Promise containing vNext network details
1773
+ */
1774
+ details() {
1775
+ return this.request(`/api/networks/v-next/${this.networkId}`);
1776
+ }
1777
+ /**
1778
+ * Generates a response from the v-next network
1779
+ * @param params - Generation parameters including message
1780
+ * @returns Promise containing the generated response
1781
+ */
1782
+ generate(params) {
1783
+ return this.request(`/api/networks/v-next/${this.networkId}/generate`, {
1784
+ method: "POST",
1785
+ body: {
1786
+ ...params,
1787
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1788
+ }
1789
+ });
1790
+ }
1791
+ /**
1792
+ * Generates a response from the v-next network using multiple primitives
1793
+ * @param params - Generation parameters including message
1794
+ * @returns Promise containing the generated response
1795
+ */
1796
+ loop(params) {
1797
+ return this.request(`/api/networks/v-next/${this.networkId}/loop`, {
1798
+ method: "POST",
1799
+ body: {
1800
+ ...params,
1801
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1802
+ }
1803
+ });
1804
+ }
1805
+ async *streamProcessor(stream) {
1806
+ const reader = stream.getReader();
1807
+ let doneReading = false;
1808
+ let buffer = "";
1809
+ try {
1810
+ while (!doneReading) {
1811
+ const { done, value } = await reader.read();
1812
+ doneReading = done;
1813
+ if (done && !value) continue;
1814
+ try {
1815
+ const decoded = value ? new TextDecoder().decode(value) : "";
1816
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR3);
1817
+ buffer = chunks.pop() || "";
1818
+ for (const chunk of chunks) {
1819
+ if (chunk) {
1820
+ if (typeof chunk === "string") {
1821
+ try {
1822
+ const parsedChunk = JSON.parse(chunk);
1823
+ yield parsedChunk;
1824
+ } catch {
1825
+ }
1826
+ }
1827
+ }
1828
+ }
1829
+ } catch {
1830
+ }
1831
+ }
1832
+ if (buffer) {
1833
+ try {
1834
+ yield JSON.parse(buffer);
1835
+ } catch {
1836
+ }
1837
+ }
1838
+ } finally {
1839
+ reader.cancel().catch(() => {
1840
+ });
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Streams a response from the v-next network
1845
+ * @param params - Stream parameters including message
1846
+ * @returns Promise containing the results
1847
+ */
1848
+ async stream(params, onRecord) {
1849
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/stream`, {
1850
+ method: "POST",
1851
+ body: {
1852
+ ...params,
1853
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1854
+ },
1855
+ stream: true
1856
+ });
1857
+ if (!response.ok) {
1858
+ throw new Error(`Failed to stream vNext network: ${response.statusText}`);
1859
+ }
1860
+ if (!response.body) {
1861
+ throw new Error("Response body is null");
1862
+ }
1863
+ for await (const record of this.streamProcessor(response.body)) {
1864
+ if (typeof record === "string") {
1865
+ onRecord(JSON.parse(record));
1866
+ } else {
1867
+ onRecord(record);
1868
+ }
1869
+ }
1870
+ }
1871
+ /**
1872
+ * Streams a response from the v-next network loop
1873
+ * @param params - Stream parameters including message
1874
+ * @returns Promise containing the results
1875
+ */
1876
+ async loopStream(params, onRecord) {
1877
+ const response = await this.request(`/api/networks/v-next/${this.networkId}/loop-stream`, {
1878
+ method: "POST",
1879
+ body: {
1880
+ ...params,
1881
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
1882
+ },
1883
+ stream: true
1884
+ });
1885
+ if (!response.ok) {
1886
+ throw new Error(`Failed to stream vNext network loop: ${response.statusText}`);
1887
+ }
1888
+ if (!response.body) {
1889
+ throw new Error("Response body is null");
1890
+ }
1891
+ for await (const record of this.streamProcessor(response.body)) {
1892
+ if (typeof record === "string") {
1893
+ onRecord(JSON.parse(record));
1894
+ } else {
1895
+ onRecord(record);
1896
+ }
1897
+ }
1898
+ }
1899
+ };
724
1900
 
725
1901
  // src/client.ts
726
1902
  var MastraClient = class extends BaseResource {
@@ -734,6 +1910,21 @@ var MastraClient = class extends BaseResource {
734
1910
  getAgents() {
735
1911
  return this.request("/api/agents");
736
1912
  }
1913
+ async getAGUI({ resourceId }) {
1914
+ const agents = await this.getAgents();
1915
+ return Object.entries(agents).reduce(
1916
+ (acc, [agentId]) => {
1917
+ const agent = this.getAgent(agentId);
1918
+ acc[agentId] = new AGUIAdapter({
1919
+ agentId,
1920
+ agent,
1921
+ resourceId
1922
+ });
1923
+ return acc;
1924
+ },
1925
+ {}
1926
+ );
1927
+ }
737
1928
  /**
738
1929
  * Gets an agent instance by ID
739
1930
  * @param agentId - ID of the agent to retrieve
@@ -784,6 +1975,48 @@ var MastraClient = class extends BaseResource {
784
1975
  getMemoryStatus(agentId) {
785
1976
  return this.request(`/api/memory/status?agentId=${agentId}`);
786
1977
  }
1978
+ /**
1979
+ * Retrieves memory threads for a resource
1980
+ * @param params - Parameters containing the resource ID
1981
+ * @returns Promise containing array of memory threads
1982
+ */
1983
+ getNetworkMemoryThreads(params) {
1984
+ return this.request(`/api/memory/network/threads?resourceid=${params.resourceId}&networkId=${params.networkId}`);
1985
+ }
1986
+ /**
1987
+ * Creates a new memory thread
1988
+ * @param params - Parameters for creating the memory thread
1989
+ * @returns Promise containing the created memory thread
1990
+ */
1991
+ createNetworkMemoryThread(params) {
1992
+ return this.request(`/api/memory/network/threads?networkId=${params.networkId}`, { method: "POST", body: params });
1993
+ }
1994
+ /**
1995
+ * Gets a memory thread instance by ID
1996
+ * @param threadId - ID of the memory thread to retrieve
1997
+ * @returns MemoryThread instance
1998
+ */
1999
+ getNetworkMemoryThread(threadId, networkId) {
2000
+ return new NetworkMemoryThread(this.options, threadId, networkId);
2001
+ }
2002
+ /**
2003
+ * Saves messages to memory
2004
+ * @param params - Parameters containing messages to save
2005
+ * @returns Promise containing the saved messages
2006
+ */
2007
+ saveNetworkMessageToMemory(params) {
2008
+ return this.request(`/api/memory/network/save-messages?networkId=${params.networkId}`, {
2009
+ method: "POST",
2010
+ body: params
2011
+ });
2012
+ }
2013
+ /**
2014
+ * Gets the status of the memory system
2015
+ * @returns Promise containing memory system status
2016
+ */
2017
+ getNetworkMemoryStatus(networkId) {
2018
+ return this.request(`/api/memory/network/status?networkId=${networkId}`);
2019
+ }
787
2020
  /**
788
2021
  * Retrieves all available tools
789
2022
  * @returns Promise containing map of tool IDs to tool details
@@ -797,7 +2030,22 @@ var MastraClient = class extends BaseResource {
797
2030
  * @returns Tool instance
798
2031
  */
799
2032
  getTool(toolId) {
800
- return new Tool(this.options, toolId);
2033
+ return new Tool2(this.options, toolId);
2034
+ }
2035
+ /**
2036
+ * Retrieves all available legacy workflows
2037
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
2038
+ */
2039
+ getLegacyWorkflows() {
2040
+ return this.request("/api/workflows/legacy");
2041
+ }
2042
+ /**
2043
+ * Gets a legacy workflow instance by ID
2044
+ * @param workflowId - ID of the legacy workflow to retrieve
2045
+ * @returns Legacy Workflow instance
2046
+ */
2047
+ getLegacyWorkflow(workflowId) {
2048
+ return new LegacyWorkflow(this.options, workflowId);
801
2049
  }
802
2050
  /**
803
2051
  * Retrieves all available workflows
@@ -814,21 +2062,6 @@ var MastraClient = class extends BaseResource {
814
2062
  getWorkflow(workflowId) {
815
2063
  return new Workflow(this.options, workflowId);
816
2064
  }
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
2065
  /**
833
2066
  * Gets a vector instance by name
834
2067
  * @param vectorName - Name of the vector to retrieve
@@ -843,7 +2076,41 @@ var MastraClient = class extends BaseResource {
843
2076
  * @returns Promise containing array of log messages
844
2077
  */
845
2078
  getLogs(params) {
846
- return this.request(`/api/logs?transportId=${params.transportId}`);
2079
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2080
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2081
+ const searchParams = new URLSearchParams();
2082
+ if (transportId) {
2083
+ searchParams.set("transportId", transportId);
2084
+ }
2085
+ if (fromDate) {
2086
+ searchParams.set("fromDate", fromDate.toISOString());
2087
+ }
2088
+ if (toDate) {
2089
+ searchParams.set("toDate", toDate.toISOString());
2090
+ }
2091
+ if (logLevel) {
2092
+ searchParams.set("logLevel", logLevel);
2093
+ }
2094
+ if (page) {
2095
+ searchParams.set("page", String(page));
2096
+ }
2097
+ if (perPage) {
2098
+ searchParams.set("perPage", String(perPage));
2099
+ }
2100
+ if (_filters) {
2101
+ if (Array.isArray(_filters)) {
2102
+ for (const filter of _filters) {
2103
+ searchParams.append("filters", filter);
2104
+ }
2105
+ } else {
2106
+ searchParams.set("filters", _filters);
2107
+ }
2108
+ }
2109
+ if (searchParams.size) {
2110
+ return this.request(`/api/logs?${searchParams}`);
2111
+ } else {
2112
+ return this.request(`/api/logs`);
2113
+ }
847
2114
  }
848
2115
  /**
849
2116
  * Gets logs for a specific run
@@ -851,7 +2118,44 @@ var MastraClient = class extends BaseResource {
851
2118
  * @returns Promise containing array of log messages
852
2119
  */
853
2120
  getLogForRun(params) {
854
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
2121
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
2122
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
2123
+ const searchParams = new URLSearchParams();
2124
+ if (runId) {
2125
+ searchParams.set("runId", runId);
2126
+ }
2127
+ if (transportId) {
2128
+ searchParams.set("transportId", transportId);
2129
+ }
2130
+ if (fromDate) {
2131
+ searchParams.set("fromDate", fromDate.toISOString());
2132
+ }
2133
+ if (toDate) {
2134
+ searchParams.set("toDate", toDate.toISOString());
2135
+ }
2136
+ if (logLevel) {
2137
+ searchParams.set("logLevel", logLevel);
2138
+ }
2139
+ if (page) {
2140
+ searchParams.set("page", String(page));
2141
+ }
2142
+ if (perPage) {
2143
+ searchParams.set("perPage", String(perPage));
2144
+ }
2145
+ if (_filters) {
2146
+ if (Array.isArray(_filters)) {
2147
+ for (const filter of _filters) {
2148
+ searchParams.append("filters", filter);
2149
+ }
2150
+ } else {
2151
+ searchParams.set("filters", _filters);
2152
+ }
2153
+ }
2154
+ if (searchParams.size) {
2155
+ return this.request(`/api/logs/${runId}?${searchParams}`);
2156
+ } else {
2157
+ return this.request(`/api/logs/${runId}`);
2158
+ }
855
2159
  }
856
2160
  /**
857
2161
  * List of all log transports
@@ -866,7 +2170,7 @@ var MastraClient = class extends BaseResource {
866
2170
  * @returns Promise containing telemetry data
867
2171
  */
868
2172
  getTelemetry(params) {
869
- const { name, scope, page, perPage, attribute } = params || {};
2173
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
870
2174
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
871
2175
  const searchParams = new URLSearchParams();
872
2176
  if (name) {
@@ -890,6 +2194,12 @@ var MastraClient = class extends BaseResource {
890
2194
  searchParams.set("attribute", _attribute);
891
2195
  }
892
2196
  }
2197
+ if (fromDate) {
2198
+ searchParams.set("fromDate", fromDate.toISOString());
2199
+ }
2200
+ if (toDate) {
2201
+ searchParams.set("toDate", toDate.toISOString());
2202
+ }
893
2203
  if (searchParams.size) {
894
2204
  return this.request(`/api/telemetry?${searchParams}`);
895
2205
  } else {
@@ -903,6 +2213,13 @@ var MastraClient = class extends BaseResource {
903
2213
  getNetworks() {
904
2214
  return this.request("/api/networks");
905
2215
  }
2216
+ /**
2217
+ * Retrieves all available vNext networks
2218
+ * @returns Promise containing map of vNext network IDs to vNext network details
2219
+ */
2220
+ getVNextNetworks() {
2221
+ return this.request("/api/networks/v-next");
2222
+ }
906
2223
  /**
907
2224
  * Gets a network instance by ID
908
2225
  * @param networkId - ID of the network to retrieve
@@ -911,6 +2228,183 @@ var MastraClient = class extends BaseResource {
911
2228
  getNetwork(networkId) {
912
2229
  return new Network(this.options, networkId);
913
2230
  }
2231
+ /**
2232
+ * Gets a vNext network instance by ID
2233
+ * @param networkId - ID of the vNext network to retrieve
2234
+ * @returns vNext Network instance
2235
+ */
2236
+ getVNextNetwork(networkId) {
2237
+ return new VNextNetwork(this.options, networkId);
2238
+ }
2239
+ /**
2240
+ * Retrieves a list of available MCP servers.
2241
+ * @param params - Optional parameters for pagination (limit, offset).
2242
+ * @returns Promise containing the list of MCP servers and pagination info.
2243
+ */
2244
+ getMcpServers(params) {
2245
+ const searchParams = new URLSearchParams();
2246
+ if (params?.limit !== void 0) {
2247
+ searchParams.set("limit", String(params.limit));
2248
+ }
2249
+ if (params?.offset !== void 0) {
2250
+ searchParams.set("offset", String(params.offset));
2251
+ }
2252
+ const queryString = searchParams.toString();
2253
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
2254
+ }
2255
+ /**
2256
+ * Retrieves detailed information for a specific MCP server.
2257
+ * @param serverId - The ID of the MCP server to retrieve.
2258
+ * @param params - Optional parameters, e.g., specific version.
2259
+ * @returns Promise containing the detailed MCP server information.
2260
+ */
2261
+ getMcpServerDetails(serverId, params) {
2262
+ const searchParams = new URLSearchParams();
2263
+ if (params?.version) {
2264
+ searchParams.set("version", params.version);
2265
+ }
2266
+ const queryString = searchParams.toString();
2267
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
2268
+ }
2269
+ /**
2270
+ * Retrieves a list of tools for a specific MCP server.
2271
+ * @param serverId - The ID of the MCP server.
2272
+ * @returns Promise containing the list of tools.
2273
+ */
2274
+ getMcpServerTools(serverId) {
2275
+ return this.request(`/api/mcp/${serverId}/tools`);
2276
+ }
2277
+ /**
2278
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
2279
+ * This instance can then be used to fetch details or execute the tool.
2280
+ * @param serverId - The ID of the MCP server.
2281
+ * @param toolId - The ID of the tool.
2282
+ * @returns MCPTool instance.
2283
+ */
2284
+ getMcpServerTool(serverId, toolId) {
2285
+ return new MCPTool(this.options, serverId, toolId);
2286
+ }
2287
+ /**
2288
+ * Gets an A2A client for interacting with an agent via the A2A protocol
2289
+ * @param agentId - ID of the agent to interact with
2290
+ * @returns A2A client instance
2291
+ */
2292
+ getA2A(agentId) {
2293
+ return new A2A(this.options, agentId);
2294
+ }
2295
+ /**
2296
+ * Retrieves the working memory for a specific thread (optionally resource-scoped).
2297
+ * @param agentId - ID of the agent.
2298
+ * @param threadId - ID of the thread.
2299
+ * @param resourceId - Optional ID of the resource.
2300
+ * @returns Working memory for the specified thread or resource.
2301
+ */
2302
+ getWorkingMemory({
2303
+ agentId,
2304
+ threadId,
2305
+ resourceId
2306
+ }) {
2307
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}&resourceId=${resourceId}`);
2308
+ }
2309
+ /**
2310
+ * Updates the working memory for a specific thread (optionally resource-scoped).
2311
+ * @param agentId - ID of the agent.
2312
+ * @param threadId - ID of the thread.
2313
+ * @param workingMemory - The new working memory content.
2314
+ * @param resourceId - Optional ID of the resource.
2315
+ */
2316
+ updateWorkingMemory({
2317
+ agentId,
2318
+ threadId,
2319
+ workingMemory,
2320
+ resourceId
2321
+ }) {
2322
+ return this.request(`/api/memory/threads/${threadId}/working-memory?agentId=${agentId}`, {
2323
+ method: "POST",
2324
+ body: {
2325
+ workingMemory,
2326
+ resourceId
2327
+ }
2328
+ });
2329
+ }
2330
+ /**
2331
+ * Retrieves all available scorers
2332
+ * @returns Promise containing list of available scorers
2333
+ */
2334
+ getScorers() {
2335
+ return this.request("/api/scores/scorers");
2336
+ }
2337
+ /**
2338
+ * Retrieves a scorer by ID
2339
+ * @param scorerId - ID of the scorer to retrieve
2340
+ * @returns Promise containing the scorer
2341
+ */
2342
+ getScorer(scorerId) {
2343
+ return this.request(`/api/scores/scorers/${scorerId}`);
2344
+ }
2345
+ getScoresByScorerId(params) {
2346
+ const { page, perPage, scorerId, entityId, entityType } = params;
2347
+ const searchParams = new URLSearchParams();
2348
+ if (entityId) {
2349
+ searchParams.set("entityId", entityId);
2350
+ }
2351
+ if (entityType) {
2352
+ searchParams.set("entityType", entityType);
2353
+ }
2354
+ if (page !== void 0) {
2355
+ searchParams.set("page", String(page));
2356
+ }
2357
+ if (perPage !== void 0) {
2358
+ searchParams.set("perPage", String(perPage));
2359
+ }
2360
+ const queryString = searchParams.toString();
2361
+ return this.request(`/api/scores/scorer/${scorerId}${queryString ? `?${queryString}` : ""}`);
2362
+ }
2363
+ /**
2364
+ * Retrieves scores by run ID
2365
+ * @param params - Parameters containing run ID and pagination options
2366
+ * @returns Promise containing scores and pagination info
2367
+ */
2368
+ getScoresByRunId(params) {
2369
+ const { runId, page, perPage } = params;
2370
+ const searchParams = new URLSearchParams();
2371
+ if (page !== void 0) {
2372
+ searchParams.set("page", String(page));
2373
+ }
2374
+ if (perPage !== void 0) {
2375
+ searchParams.set("perPage", String(perPage));
2376
+ }
2377
+ const queryString = searchParams.toString();
2378
+ return this.request(`/api/scores/run/${runId}${queryString ? `?${queryString}` : ""}`);
2379
+ }
2380
+ /**
2381
+ * Retrieves scores by entity ID and type
2382
+ * @param params - Parameters containing entity ID, type, and pagination options
2383
+ * @returns Promise containing scores and pagination info
2384
+ */
2385
+ getScoresByEntityId(params) {
2386
+ const { entityId, entityType, page, perPage } = params;
2387
+ const searchParams = new URLSearchParams();
2388
+ if (page !== void 0) {
2389
+ searchParams.set("page", String(page));
2390
+ }
2391
+ if (perPage !== void 0) {
2392
+ searchParams.set("perPage", String(perPage));
2393
+ }
2394
+ const queryString = searchParams.toString();
2395
+ return this.request(`/api/scores/entity/${entityType}/${entityId}${queryString ? `?${queryString}` : ""}`);
2396
+ }
2397
+ /**
2398
+ * Saves a score
2399
+ * @param params - Parameters containing the score data to save
2400
+ * @returns Promise containing the saved score
2401
+ */
2402
+ saveScore(params) {
2403
+ return this.request("/api/scores", {
2404
+ method: "POST",
2405
+ body: params
2406
+ });
2407
+ }
914
2408
  };
915
2409
 
916
2410
  export { MastraClient };