@mastra/client-js 0.10.12 → 0.10.14-alpha.0

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