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