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