@mastra/client-js 0.0.0-storage-20250225005900 → 0.0.0-support-d1-client-20250701191943

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