@mastra/client-js 0.10.11 → 0.10.12

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