@mastra/client-js 0.0.0-commonjs-20250227130920 → 0.0.0-course-20250527170450

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 CHANGED
@@ -1,7 +1,201 @@
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
+ import { processDataStream } from '@ai-sdk/ui-utils';
1
4
  import { ZodSchema } from 'zod';
2
- import { zodToJsonSchema } from 'zod-to-json-schema';
5
+ import originalZodToJsonSchema from 'zod-to-json-schema';
6
+ import { RuntimeContext } from '@mastra/core/runtime-context';
3
7
 
4
- // src/resources/agent.ts
8
+ // src/adapters/agui.ts
9
+ var AGUIAdapter = class extends AbstractAgent {
10
+ agent;
11
+ resourceId;
12
+ constructor({ agent, agentId, resourceId, ...rest }) {
13
+ super({
14
+ agentId,
15
+ ...rest
16
+ });
17
+ this.agent = agent;
18
+ this.resourceId = resourceId;
19
+ }
20
+ run(input) {
21
+ return new Observable((subscriber) => {
22
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
23
+ subscriber.next({
24
+ type: EventType.RUN_STARTED,
25
+ threadId: input.threadId,
26
+ runId: input.runId
27
+ });
28
+ this.agent.stream({
29
+ threadId: input.threadId,
30
+ resourceId: this.resourceId ?? "",
31
+ runId: input.runId,
32
+ messages: convertedMessages,
33
+ clientTools: input.tools.reduce(
34
+ (acc, tool) => {
35
+ acc[tool.name] = {
36
+ id: tool.name,
37
+ description: tool.description,
38
+ inputSchema: tool.parameters
39
+ };
40
+ return acc;
41
+ },
42
+ {}
43
+ )
44
+ }).then((response) => {
45
+ let currentMessageId = void 0;
46
+ let isInTextMessage = false;
47
+ return response.processDataStream({
48
+ onTextPart: (text) => {
49
+ if (currentMessageId === void 0) {
50
+ currentMessageId = generateUUID();
51
+ const message2 = {
52
+ type: EventType.TEXT_MESSAGE_START,
53
+ messageId: currentMessageId,
54
+ role: "assistant"
55
+ };
56
+ subscriber.next(message2);
57
+ isInTextMessage = true;
58
+ }
59
+ const message = {
60
+ type: EventType.TEXT_MESSAGE_CONTENT,
61
+ messageId: currentMessageId,
62
+ delta: text
63
+ };
64
+ subscriber.next(message);
65
+ },
66
+ onFinishMessagePart: () => {
67
+ if (currentMessageId !== void 0) {
68
+ const message = {
69
+ type: EventType.TEXT_MESSAGE_END,
70
+ messageId: currentMessageId
71
+ };
72
+ subscriber.next(message);
73
+ isInTextMessage = false;
74
+ }
75
+ subscriber.next({
76
+ type: EventType.RUN_FINISHED,
77
+ threadId: input.threadId,
78
+ runId: input.runId
79
+ });
80
+ subscriber.complete();
81
+ },
82
+ onToolCallPart(streamPart) {
83
+ const parentMessageId = currentMessageId || generateUUID();
84
+ if (isInTextMessage) {
85
+ const message = {
86
+ type: EventType.TEXT_MESSAGE_END,
87
+ messageId: parentMessageId
88
+ };
89
+ subscriber.next(message);
90
+ isInTextMessage = false;
91
+ }
92
+ subscriber.next({
93
+ type: EventType.TOOL_CALL_START,
94
+ toolCallId: streamPart.toolCallId,
95
+ toolCallName: streamPart.toolName,
96
+ parentMessageId
97
+ });
98
+ subscriber.next({
99
+ type: EventType.TOOL_CALL_ARGS,
100
+ toolCallId: streamPart.toolCallId,
101
+ delta: JSON.stringify(streamPart.args),
102
+ parentMessageId
103
+ });
104
+ subscriber.next({
105
+ type: EventType.TOOL_CALL_END,
106
+ toolCallId: streamPart.toolCallId,
107
+ parentMessageId
108
+ });
109
+ }
110
+ });
111
+ }).catch((error) => {
112
+ console.error("error", error);
113
+ subscriber.error(error);
114
+ });
115
+ return () => {
116
+ };
117
+ });
118
+ }
119
+ };
120
+ function generateUUID() {
121
+ if (typeof crypto !== "undefined") {
122
+ if (typeof crypto.randomUUID === "function") {
123
+ return crypto.randomUUID();
124
+ }
125
+ if (typeof crypto.getRandomValues === "function") {
126
+ const buffer = new Uint8Array(16);
127
+ crypto.getRandomValues(buffer);
128
+ buffer[6] = buffer[6] & 15 | 64;
129
+ buffer[8] = buffer[8] & 63 | 128;
130
+ let hex = "";
131
+ for (let i = 0; i < 16; i++) {
132
+ hex += buffer[i].toString(16).padStart(2, "0");
133
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
134
+ }
135
+ return hex;
136
+ }
137
+ }
138
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
139
+ const r = Math.random() * 16 | 0;
140
+ const v = c === "x" ? r : r & 3 | 8;
141
+ return v.toString(16);
142
+ });
143
+ }
144
+ function convertMessagesToMastraMessages(messages) {
145
+ const result = [];
146
+ for (const message of messages) {
147
+ if (message.role === "assistant") {
148
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
149
+ for (const toolCall of message.toolCalls ?? []) {
150
+ parts.push({
151
+ type: "tool-call",
152
+ toolCallId: toolCall.id,
153
+ toolName: toolCall.function.name,
154
+ args: JSON.parse(toolCall.function.arguments)
155
+ });
156
+ }
157
+ result.push({
158
+ role: "assistant",
159
+ content: parts
160
+ });
161
+ if (message.toolCalls?.length) {
162
+ result.push({
163
+ role: "tool",
164
+ content: message.toolCalls.map((toolCall) => ({
165
+ type: "tool-result",
166
+ toolCallId: toolCall.id,
167
+ toolName: toolCall.function.name,
168
+ result: JSON.parse(toolCall.function.arguments)
169
+ }))
170
+ });
171
+ }
172
+ } else if (message.role === "user") {
173
+ result.push({
174
+ role: "user",
175
+ content: message.content || ""
176
+ });
177
+ } else if (message.role === "tool") {
178
+ result.push({
179
+ role: "tool",
180
+ content: [
181
+ {
182
+ type: "tool-result",
183
+ toolCallId: message.toolCallId,
184
+ toolName: "unknown",
185
+ result: message.content
186
+ }
187
+ ]
188
+ });
189
+ }
190
+ }
191
+ return result;
192
+ }
193
+ function zodToJsonSchema(zodSchema) {
194
+ if (!(zodSchema instanceof ZodSchema)) {
195
+ return zodSchema;
196
+ }
197
+ return originalZodToJsonSchema(zodSchema, { $refStrategy: "none" });
198
+ }
5
199
 
6
200
  // src/resources/base.ts
7
201
  var BaseResource = class {
@@ -21,14 +215,15 @@ var BaseResource = class {
21
215
  let delay = backoffMs;
22
216
  for (let attempt = 0; attempt <= retries; attempt++) {
23
217
  try {
24
- const response = await fetch(`${baseUrl}${path}`, {
218
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
25
219
  ...options,
26
220
  headers: {
27
- "Content-Type": "application/json",
28
221
  ...headers,
29
222
  ...options.headers
223
+ // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
224
+ // 'x-mastra-client-type': 'js',
30
225
  },
31
- body: options.body ? JSON.stringify(options.body) : void 0
226
+ body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
32
227
  });
33
228
  if (!response.ok) {
34
229
  const errorBody = await response.text();
@@ -60,13 +255,71 @@ var BaseResource = class {
60
255
  throw lastError || new Error("Request failed");
61
256
  }
62
257
  };
258
+ function parseClientRuntimeContext(runtimeContext) {
259
+ if (runtimeContext) {
260
+ if (runtimeContext instanceof RuntimeContext) {
261
+ return Object.fromEntries(runtimeContext.entries());
262
+ }
263
+ return runtimeContext;
264
+ }
265
+ return void 0;
266
+ }
63
267
 
64
268
  // src/resources/agent.ts
269
+ var AgentVoice = class extends BaseResource {
270
+ constructor(options, agentId) {
271
+ super(options);
272
+ this.agentId = agentId;
273
+ this.agentId = agentId;
274
+ }
275
+ /**
276
+ * Convert text to speech using the agent's voice provider
277
+ * @param text - Text to convert to speech
278
+ * @param options - Optional provider-specific options for speech generation
279
+ * @returns Promise containing the audio data
280
+ */
281
+ async speak(text, options) {
282
+ return this.request(`/api/agents/${this.agentId}/voice/speak`, {
283
+ method: "POST",
284
+ headers: {
285
+ "Content-Type": "application/json"
286
+ },
287
+ body: { input: text, options },
288
+ stream: true
289
+ });
290
+ }
291
+ /**
292
+ * Convert speech to text using the agent's voice provider
293
+ * @param audio - Audio data to transcribe
294
+ * @param options - Optional provider-specific options
295
+ * @returns Promise containing the transcribed text
296
+ */
297
+ listen(audio, options) {
298
+ const formData = new FormData();
299
+ formData.append("audio", audio);
300
+ if (options) {
301
+ formData.append("options", JSON.stringify(options));
302
+ }
303
+ return this.request(`/api/agents/${this.agentId}/voice/listen`, {
304
+ method: "POST",
305
+ body: formData
306
+ });
307
+ }
308
+ /**
309
+ * Get available speakers for the agent's voice provider
310
+ * @returns Promise containing list of available speakers
311
+ */
312
+ getSpeakers() {
313
+ return this.request(`/api/agents/${this.agentId}/voice/speakers`);
314
+ }
315
+ };
65
316
  var Agent = class extends BaseResource {
66
317
  constructor(options, agentId) {
67
318
  super(options);
68
319
  this.agentId = agentId;
320
+ this.voice = new AgentVoice(options, this.agentId);
69
321
  }
322
+ voice;
70
323
  /**
71
324
  * Retrieves details about the agent
72
325
  * @returns Promise containing agent details including model and instructions
@@ -82,7 +335,9 @@ var Agent = class extends BaseResource {
82
335
  generate(params) {
83
336
  const processedParams = {
84
337
  ...params,
85
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output
338
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
339
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
340
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
86
341
  };
87
342
  return this.request(`/api/agents/${this.agentId}/generate`, {
88
343
  method: "POST",
@@ -92,18 +347,30 @@ var Agent = class extends BaseResource {
92
347
  /**
93
348
  * Streams a response from the agent
94
349
  * @param params - Stream parameters including prompt
95
- * @returns Promise containing the streamed response
350
+ * @returns Promise containing the enhanced Response object with processDataStream method
96
351
  */
97
- stream(params) {
352
+ async stream(params) {
98
353
  const processedParams = {
99
354
  ...params,
100
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output
355
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
356
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
357
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
101
358
  };
102
- return this.request(`/api/agents/${this.agentId}/stream`, {
359
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
103
360
  method: "POST",
104
361
  body: processedParams,
105
362
  stream: true
106
363
  });
364
+ if (!response.body) {
365
+ throw new Error("No response body");
366
+ }
367
+ response.processDataStream = async (options = {}) => {
368
+ await processDataStream({
369
+ stream: response.body,
370
+ ...options
371
+ });
372
+ };
373
+ return response;
107
374
  }
108
375
  /**
109
376
  * Gets details about a specific tool available to the agent
@@ -113,6 +380,22 @@ var Agent = class extends BaseResource {
113
380
  getTool(toolId) {
114
381
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
115
382
  }
383
+ /**
384
+ * Executes a tool for the agent
385
+ * @param toolId - ID of the tool to execute
386
+ * @param params - Parameters required for tool execution
387
+ * @returns Promise containing the tool execution results
388
+ */
389
+ executeTool(toolId, params) {
390
+ const body = {
391
+ data: params.data,
392
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
393
+ };
394
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
395
+ method: "POST",
396
+ body
397
+ });
398
+ }
116
399
  /**
117
400
  * Retrieves evaluation results for the agent
118
401
  * @returns Promise containing agent evaluations
@@ -128,6 +411,62 @@ var Agent = class extends BaseResource {
128
411
  return this.request(`/api/agents/${this.agentId}/evals/live`);
129
412
  }
130
413
  };
414
+ var Network = class extends BaseResource {
415
+ constructor(options, networkId) {
416
+ super(options);
417
+ this.networkId = networkId;
418
+ }
419
+ /**
420
+ * Retrieves details about the network
421
+ * @returns Promise containing network details
422
+ */
423
+ details() {
424
+ return this.request(`/api/networks/${this.networkId}`);
425
+ }
426
+ /**
427
+ * Generates a response from the agent
428
+ * @param params - Generation parameters including prompt
429
+ * @returns Promise containing the generated response
430
+ */
431
+ generate(params) {
432
+ const processedParams = {
433
+ ...params,
434
+ output: zodToJsonSchema(params.output),
435
+ experimental_output: zodToJsonSchema(params.experimental_output)
436
+ };
437
+ return this.request(`/api/networks/${this.networkId}/generate`, {
438
+ method: "POST",
439
+ body: processedParams
440
+ });
441
+ }
442
+ /**
443
+ * Streams a response from the agent
444
+ * @param params - Stream parameters including prompt
445
+ * @returns Promise containing the enhanced Response object with processDataStream method
446
+ */
447
+ async stream(params) {
448
+ const processedParams = {
449
+ ...params,
450
+ output: zodToJsonSchema(params.output),
451
+ experimental_output: zodToJsonSchema(params.experimental_output)
452
+ };
453
+ const response = await this.request(`/api/networks/${this.networkId}/stream`, {
454
+ method: "POST",
455
+ body: processedParams,
456
+ stream: true
457
+ });
458
+ if (!response.body) {
459
+ throw new Error("No response body");
460
+ }
461
+ response.processDataStream = async (options = {}) => {
462
+ await processDataStream({
463
+ stream: response.body,
464
+ ...options
465
+ });
466
+ };
467
+ return response;
468
+ }
469
+ };
131
470
 
132
471
  // src/resources/memory-thread.ts
133
472
  var MemoryThread = class extends BaseResource {
@@ -165,10 +504,15 @@ var MemoryThread = class extends BaseResource {
165
504
  }
166
505
  /**
167
506
  * Retrieves messages associated with the thread
507
+ * @param params - Optional parameters including limit for number of messages to retrieve
168
508
  * @returns Promise containing thread messages and UI messages
169
509
  */
170
- getMessages() {
171
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
510
+ getMessages(params) {
511
+ const query = new URLSearchParams({
512
+ agentId: this.agentId,
513
+ ...params?.limit ? { limit: params.limit.toString() } : {}
514
+ });
515
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
172
516
  }
173
517
  };
174
518
 
@@ -238,59 +582,184 @@ var Vector = class extends BaseResource {
238
582
  }
239
583
  };
240
584
 
241
- // src/resources/workflow.ts
242
- var Workflow = class extends BaseResource {
585
+ // src/resources/legacy-workflow.ts
586
+ var RECORD_SEPARATOR = "";
587
+ var LegacyWorkflow = class extends BaseResource {
243
588
  constructor(options, workflowId) {
244
589
  super(options);
245
590
  this.workflowId = workflowId;
246
591
  }
247
592
  /**
248
- * Retrieves details about the workflow
249
- * @returns Promise containing workflow details including steps and graphs
593
+ * Retrieves details about the legacy workflow
594
+ * @returns Promise containing legacy workflow details including steps and graphs
250
595
  */
251
596
  details() {
252
- return this.request(`/api/workflows/${this.workflowId}`);
597
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
253
598
  }
254
599
  /**
255
- * Executes the workflow with the provided parameters
256
- * @param params - Parameters required for workflow execution
257
- * @returns Promise containing the workflow execution results
600
+ * Retrieves all runs for a legacy workflow
601
+ * @param params - Parameters for filtering runs
602
+ * @returns Promise containing legacy workflow runs array
258
603
  */
259
- execute(params) {
260
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
604
+ runs(params) {
605
+ const searchParams = new URLSearchParams();
606
+ if (params?.fromDate) {
607
+ searchParams.set("fromDate", params.fromDate.toISOString());
608
+ }
609
+ if (params?.toDate) {
610
+ searchParams.set("toDate", params.toDate.toISOString());
611
+ }
612
+ if (params?.limit) {
613
+ searchParams.set("limit", String(params.limit));
614
+ }
615
+ if (params?.offset) {
616
+ searchParams.set("offset", String(params.offset));
617
+ }
618
+ if (params?.resourceId) {
619
+ searchParams.set("resourceId", params.resourceId);
620
+ }
621
+ if (searchParams.size) {
622
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
623
+ } else {
624
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
625
+ }
626
+ }
627
+ /**
628
+ * Creates a new legacy workflow run
629
+ * @returns Promise containing the generated run ID
630
+ */
631
+ createRun(params) {
632
+ const searchParams = new URLSearchParams();
633
+ if (!!params?.runId) {
634
+ searchParams.set("runId", params.runId);
635
+ }
636
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
637
+ method: "POST"
638
+ });
639
+ }
640
+ /**
641
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
642
+ * @param params - Object containing the runId and triggerData
643
+ * @returns Promise containing success message
644
+ */
645
+ start(params) {
646
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
261
647
  method: "POST",
262
- body: params
648
+ body: params?.triggerData
263
649
  });
264
650
  }
265
651
  /**
266
- * Resumes a suspended workflow step
652
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
267
653
  * @param stepId - ID of the step to resume
268
- * @param runId - ID of the workflow run
269
- * @param context - Context to resume the workflow with
270
- * @returns Promise containing the workflow resume results
654
+ * @param runId - ID of the legacy workflow run
655
+ * @param context - Context to resume the legacy workflow with
656
+ * @returns Promise containing the legacy workflow resume results
271
657
  */
272
658
  resume({
273
659
  stepId,
274
660
  runId,
275
661
  context
276
662
  }) {
277
- return this.request(`/api/workflows/${this.workflowId}/resume`, {
663
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
278
664
  method: "POST",
279
665
  body: {
280
666
  stepId,
281
- runId,
282
667
  context
283
668
  }
284
669
  });
285
670
  }
286
671
  /**
287
- * Watches workflow transitions in real-time
288
- * @returns Promise containing the workflow watch stream
672
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
673
+ * @param params - Object containing the optional runId and triggerData
674
+ * @returns Promise containing the workflow execution results
675
+ */
676
+ startAsync(params) {
677
+ const searchParams = new URLSearchParams();
678
+ if (!!params?.runId) {
679
+ searchParams.set("runId", params.runId);
680
+ }
681
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
682
+ method: "POST",
683
+ body: params?.triggerData
684
+ });
685
+ }
686
+ /**
687
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
688
+ * @param params - Object containing the runId, stepId, and context
689
+ * @returns Promise containing the workflow resume results
289
690
  */
290
- watch() {
291
- return this.request(`/api/workflows/${this.workflowId}/watch`, {
691
+ resumeAsync(params) {
692
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
693
+ method: "POST",
694
+ body: {
695
+ stepId: params.stepId,
696
+ context: params.context
697
+ }
698
+ });
699
+ }
700
+ /**
701
+ * Creates an async generator that processes a readable stream and yields records
702
+ * separated by the Record Separator character (\x1E)
703
+ *
704
+ * @param stream - The readable stream to process
705
+ * @returns An async generator that yields parsed records
706
+ */
707
+ async *streamProcessor(stream) {
708
+ const reader = stream.getReader();
709
+ let doneReading = false;
710
+ let buffer = "";
711
+ try {
712
+ while (!doneReading) {
713
+ const { done, value } = await reader.read();
714
+ doneReading = done;
715
+ if (done && !value) continue;
716
+ try {
717
+ const decoded = value ? new TextDecoder().decode(value) : "";
718
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
719
+ buffer = chunks.pop() || "";
720
+ for (const chunk of chunks) {
721
+ if (chunk) {
722
+ if (typeof chunk === "string") {
723
+ try {
724
+ const parsedChunk = JSON.parse(chunk);
725
+ yield parsedChunk;
726
+ } catch {
727
+ }
728
+ }
729
+ }
730
+ }
731
+ } catch {
732
+ }
733
+ }
734
+ if (buffer) {
735
+ try {
736
+ yield JSON.parse(buffer);
737
+ } catch {
738
+ }
739
+ }
740
+ } finally {
741
+ reader.cancel().catch(() => {
742
+ });
743
+ }
744
+ }
745
+ /**
746
+ * Watches legacy workflow transitions in real-time
747
+ * @param runId - Optional run ID to filter the watch stream
748
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
749
+ */
750
+ async watch({ runId }, onRecord) {
751
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
292
752
  stream: true
293
753
  });
754
+ if (!response.ok) {
755
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
756
+ }
757
+ if (!response.body) {
758
+ throw new Error("Response body is null");
759
+ }
760
+ for await (const record of this.streamProcessor(response.body)) {
761
+ onRecord(record);
762
+ }
294
763
  }
295
764
  };
296
765
 
@@ -313,9 +782,383 @@ var Tool = class extends BaseResource {
313
782
  * @returns Promise containing the tool execution results
314
783
  */
315
784
  execute(params) {
316
- return this.request(`/api/tools/${this.toolId}/execute`, {
785
+ const url = new URLSearchParams();
786
+ if (params.runId) {
787
+ url.set("runId", params.runId);
788
+ }
789
+ const body = {
790
+ data: params.data,
791
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
792
+ };
793
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
317
794
  method: "POST",
318
- body: params
795
+ body
796
+ });
797
+ }
798
+ };
799
+
800
+ // src/resources/workflow.ts
801
+ var RECORD_SEPARATOR2 = "";
802
+ var Workflow = class extends BaseResource {
803
+ constructor(options, workflowId) {
804
+ super(options);
805
+ this.workflowId = workflowId;
806
+ }
807
+ /**
808
+ * Creates an async generator that processes a readable stream and yields workflow records
809
+ * separated by the Record Separator character (\x1E)
810
+ *
811
+ * @param stream - The readable stream to process
812
+ * @returns An async generator that yields parsed records
813
+ */
814
+ async *streamProcessor(stream) {
815
+ const reader = stream.getReader();
816
+ let doneReading = false;
817
+ let buffer = "";
818
+ try {
819
+ while (!doneReading) {
820
+ const { done, value } = await reader.read();
821
+ doneReading = done;
822
+ if (done && !value) continue;
823
+ try {
824
+ const decoded = value ? new TextDecoder().decode(value) : "";
825
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
826
+ buffer = chunks.pop() || "";
827
+ for (const chunk of chunks) {
828
+ if (chunk) {
829
+ if (typeof chunk === "string") {
830
+ try {
831
+ const parsedChunk = JSON.parse(chunk);
832
+ yield parsedChunk;
833
+ } catch {
834
+ }
835
+ }
836
+ }
837
+ }
838
+ } catch {
839
+ }
840
+ }
841
+ if (buffer) {
842
+ try {
843
+ yield JSON.parse(buffer);
844
+ } catch {
845
+ }
846
+ }
847
+ } finally {
848
+ reader.cancel().catch(() => {
849
+ });
850
+ }
851
+ }
852
+ /**
853
+ * Retrieves details about the workflow
854
+ * @returns Promise containing workflow details including steps and graphs
855
+ */
856
+ details() {
857
+ return this.request(`/api/workflows/${this.workflowId}`);
858
+ }
859
+ /**
860
+ * Retrieves all runs for a workflow
861
+ * @param params - Parameters for filtering runs
862
+ * @returns Promise containing workflow runs array
863
+ */
864
+ runs(params) {
865
+ const searchParams = new URLSearchParams();
866
+ if (params?.fromDate) {
867
+ searchParams.set("fromDate", params.fromDate.toISOString());
868
+ }
869
+ if (params?.toDate) {
870
+ searchParams.set("toDate", params.toDate.toISOString());
871
+ }
872
+ if (params?.limit) {
873
+ searchParams.set("limit", String(params.limit));
874
+ }
875
+ if (params?.offset) {
876
+ searchParams.set("offset", String(params.offset));
877
+ }
878
+ if (params?.resourceId) {
879
+ searchParams.set("resourceId", params.resourceId);
880
+ }
881
+ if (searchParams.size) {
882
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
883
+ } else {
884
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
885
+ }
886
+ }
887
+ /**
888
+ * Creates a new workflow run
889
+ * @param params - Optional object containing the optional runId
890
+ * @returns Promise containing the runId of the created run
891
+ */
892
+ createRun(params) {
893
+ const searchParams = new URLSearchParams();
894
+ if (!!params?.runId) {
895
+ searchParams.set("runId", params.runId);
896
+ }
897
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
898
+ method: "POST"
899
+ });
900
+ }
901
+ /**
902
+ * Starts a workflow run synchronously without waiting for the workflow to complete
903
+ * @param params - Object containing the runId, inputData and runtimeContext
904
+ * @returns Promise containing success message
905
+ */
906
+ start(params) {
907
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
908
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
909
+ method: "POST",
910
+ body: { inputData: params?.inputData, runtimeContext }
911
+ });
912
+ }
913
+ /**
914
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
915
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
916
+ * @returns Promise containing success message
917
+ */
918
+ resume({
919
+ step,
920
+ runId,
921
+ resumeData,
922
+ ...rest
923
+ }) {
924
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
925
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
926
+ method: "POST",
927
+ stream: true,
928
+ body: {
929
+ step,
930
+ resumeData,
931
+ runtimeContext
932
+ }
933
+ });
934
+ }
935
+ /**
936
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
937
+ * @param params - Object containing the optional runId, inputData and runtimeContext
938
+ * @returns Promise containing the workflow execution results
939
+ */
940
+ startAsync(params) {
941
+ const searchParams = new URLSearchParams();
942
+ if (!!params?.runId) {
943
+ searchParams.set("runId", params.runId);
944
+ }
945
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
946
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
947
+ method: "POST",
948
+ body: { inputData: params.inputData, runtimeContext }
949
+ });
950
+ }
951
+ /**
952
+ * Starts a vNext workflow run and returns a stream
953
+ * @param params - Object containing the optional runId, inputData and runtimeContext
954
+ * @returns Promise containing the vNext workflow execution results
955
+ */
956
+ async stream(params) {
957
+ const searchParams = new URLSearchParams();
958
+ if (!!params?.runId) {
959
+ searchParams.set("runId", params.runId);
960
+ }
961
+ const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
962
+ const response = await this.request(
963
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
964
+ {
965
+ method: "POST",
966
+ body: { inputData: params.inputData, runtimeContext },
967
+ stream: true
968
+ }
969
+ );
970
+ if (!response.ok) {
971
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
972
+ }
973
+ if (!response.body) {
974
+ throw new Error("Response body is null");
975
+ }
976
+ const transformStream = new TransformStream({
977
+ start() {
978
+ },
979
+ async transform(chunk, controller) {
980
+ try {
981
+ const decoded = new TextDecoder().decode(chunk);
982
+ const chunks = decoded.split(RECORD_SEPARATOR2);
983
+ for (const chunk2 of chunks) {
984
+ if (chunk2) {
985
+ try {
986
+ const parsedChunk = JSON.parse(chunk2);
987
+ controller.enqueue(parsedChunk);
988
+ } catch {
989
+ }
990
+ }
991
+ }
992
+ } catch {
993
+ }
994
+ }
995
+ });
996
+ return response.body.pipeThrough(transformStream);
997
+ }
998
+ /**
999
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1000
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1001
+ * @returns Promise containing the workflow resume results
1002
+ */
1003
+ resumeAsync(params) {
1004
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1005
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1006
+ method: "POST",
1007
+ body: {
1008
+ step: params.step,
1009
+ resumeData: params.resumeData,
1010
+ runtimeContext
1011
+ }
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Watches workflow transitions in real-time
1016
+ * @param runId - Optional run ID to filter the watch stream
1017
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1018
+ */
1019
+ async watch({ runId }, onRecord) {
1020
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1021
+ stream: true
1022
+ });
1023
+ if (!response.ok) {
1024
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1025
+ }
1026
+ if (!response.body) {
1027
+ throw new Error("Response body is null");
1028
+ }
1029
+ for await (const record of this.streamProcessor(response.body)) {
1030
+ onRecord(record);
1031
+ }
1032
+ }
1033
+ /**
1034
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1035
+ * serializing each as JSON and separating them with the record separator (\x1E).
1036
+ *
1037
+ * @param records - An iterable or async iterable of objects to stream
1038
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1039
+ */
1040
+ static createRecordStream(records) {
1041
+ const encoder = new TextEncoder();
1042
+ return new ReadableStream({
1043
+ async start(controller) {
1044
+ try {
1045
+ for await (const record of records) {
1046
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1047
+ controller.enqueue(encoder.encode(json));
1048
+ }
1049
+ controller.close();
1050
+ } catch (err) {
1051
+ controller.error(err);
1052
+ }
1053
+ }
1054
+ });
1055
+ }
1056
+ };
1057
+
1058
+ // src/resources/a2a.ts
1059
+ var A2A = class extends BaseResource {
1060
+ constructor(options, agentId) {
1061
+ super(options);
1062
+ this.agentId = agentId;
1063
+ }
1064
+ /**
1065
+ * Get the agent card with metadata about the agent
1066
+ * @returns Promise containing the agent card information
1067
+ */
1068
+ async getCard() {
1069
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1070
+ }
1071
+ /**
1072
+ * Send a message to the agent and get a response
1073
+ * @param params - Parameters for the task
1074
+ * @returns Promise containing the task response
1075
+ */
1076
+ async sendMessage(params) {
1077
+ const response = await this.request(`/a2a/${this.agentId}`, {
1078
+ method: "POST",
1079
+ body: {
1080
+ method: "tasks/send",
1081
+ params
1082
+ }
1083
+ });
1084
+ return { task: response.result };
1085
+ }
1086
+ /**
1087
+ * Get the status and result of a task
1088
+ * @param params - Parameters for querying the task
1089
+ * @returns Promise containing the task response
1090
+ */
1091
+ async getTask(params) {
1092
+ const response = await this.request(`/a2a/${this.agentId}`, {
1093
+ method: "POST",
1094
+ body: {
1095
+ method: "tasks/get",
1096
+ params
1097
+ }
1098
+ });
1099
+ return response.result;
1100
+ }
1101
+ /**
1102
+ * Cancel a running task
1103
+ * @param params - Parameters identifying the task to cancel
1104
+ * @returns Promise containing the task response
1105
+ */
1106
+ async cancelTask(params) {
1107
+ return this.request(`/a2a/${this.agentId}`, {
1108
+ method: "POST",
1109
+ body: {
1110
+ method: "tasks/cancel",
1111
+ params
1112
+ }
1113
+ });
1114
+ }
1115
+ /**
1116
+ * Send a message and subscribe to streaming updates (not fully implemented)
1117
+ * @param params - Parameters for the task
1118
+ * @returns Promise containing the task response
1119
+ */
1120
+ async sendAndSubscribe(params) {
1121
+ return this.request(`/a2a/${this.agentId}`, {
1122
+ method: "POST",
1123
+ body: {
1124
+ method: "tasks/sendSubscribe",
1125
+ params
1126
+ },
1127
+ stream: true
1128
+ });
1129
+ }
1130
+ };
1131
+
1132
+ // src/resources/mcp-tool.ts
1133
+ var MCPTool = class extends BaseResource {
1134
+ serverId;
1135
+ toolId;
1136
+ constructor(options, serverId, toolId) {
1137
+ super(options);
1138
+ this.serverId = serverId;
1139
+ this.toolId = toolId;
1140
+ }
1141
+ /**
1142
+ * Retrieves details about this specific tool from the MCP server.
1143
+ * @returns Promise containing the tool's information (name, description, schema).
1144
+ */
1145
+ details() {
1146
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1147
+ }
1148
+ /**
1149
+ * Executes this specific tool on the MCP server.
1150
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1151
+ * @returns Promise containing the result of the tool execution.
1152
+ */
1153
+ execute(params) {
1154
+ const body = {};
1155
+ if (params.data !== void 0) body.data = params.data;
1156
+ if (params.runtimeContext !== void 0) {
1157
+ body.runtimeContext = params.runtimeContext;
1158
+ }
1159
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1160
+ method: "POST",
1161
+ body: Object.keys(body).length > 0 ? body : void 0
319
1162
  });
320
1163
  }
321
1164
  };
@@ -332,6 +1175,21 @@ var MastraClient = class extends BaseResource {
332
1175
  getAgents() {
333
1176
  return this.request("/api/agents");
334
1177
  }
1178
+ async getAGUI({ resourceId }) {
1179
+ const agents = await this.getAgents();
1180
+ return Object.entries(agents).reduce(
1181
+ (acc, [agentId]) => {
1182
+ const agent = this.getAgent(agentId);
1183
+ acc[agentId] = new AGUIAdapter({
1184
+ agentId,
1185
+ agent,
1186
+ resourceId
1187
+ });
1188
+ return acc;
1189
+ },
1190
+ {}
1191
+ );
1192
+ }
335
1193
  /**
336
1194
  * Gets an agent instance by ID
337
1195
  * @param agentId - ID of the agent to retrieve
@@ -397,6 +1255,21 @@ var MastraClient = class extends BaseResource {
397
1255
  getTool(toolId) {
398
1256
  return new Tool(this.options, toolId);
399
1257
  }
1258
+ /**
1259
+ * Retrieves all available legacy workflows
1260
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1261
+ */
1262
+ getLegacyWorkflows() {
1263
+ return this.request("/api/workflows/legacy");
1264
+ }
1265
+ /**
1266
+ * Gets a legacy workflow instance by ID
1267
+ * @param workflowId - ID of the legacy workflow to retrieve
1268
+ * @returns Legacy Workflow instance
1269
+ */
1270
+ getLegacyWorkflow(workflowId) {
1271
+ return new LegacyWorkflow(this.options, workflowId);
1272
+ }
400
1273
  /**
401
1274
  * Retrieves all available workflows
402
1275
  * @returns Promise containing map of workflow IDs to workflow details
@@ -449,11 +1322,8 @@ var MastraClient = class extends BaseResource {
449
1322
  * @returns Promise containing telemetry data
450
1323
  */
451
1324
  getTelemetry(params) {
452
- const { name, scope, page, perPage, attribute } = params || {};
1325
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
453
1326
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
454
- ({
455
- ..._attribute?.length ? { attribute: _attribute } : {}
456
- });
457
1327
  const searchParams = new URLSearchParams();
458
1328
  if (name) {
459
1329
  searchParams.set("name", name);
@@ -476,12 +1346,89 @@ var MastraClient = class extends BaseResource {
476
1346
  searchParams.set("attribute", _attribute);
477
1347
  }
478
1348
  }
1349
+ if (fromDate) {
1350
+ searchParams.set("fromDate", fromDate.toISOString());
1351
+ }
1352
+ if (toDate) {
1353
+ searchParams.set("toDate", toDate.toISOString());
1354
+ }
479
1355
  if (searchParams.size) {
480
1356
  return this.request(`/api/telemetry?${searchParams}`);
481
1357
  } else {
482
1358
  return this.request(`/api/telemetry`);
483
1359
  }
484
1360
  }
1361
+ /**
1362
+ * Retrieves all available networks
1363
+ * @returns Promise containing map of network IDs to network details
1364
+ */
1365
+ getNetworks() {
1366
+ return this.request("/api/networks");
1367
+ }
1368
+ /**
1369
+ * Gets a network instance by ID
1370
+ * @param networkId - ID of the network to retrieve
1371
+ * @returns Network instance
1372
+ */
1373
+ getNetwork(networkId) {
1374
+ return new Network(this.options, networkId);
1375
+ }
1376
+ /**
1377
+ * Retrieves a list of available MCP servers.
1378
+ * @param params - Optional parameters for pagination (limit, offset).
1379
+ * @returns Promise containing the list of MCP servers and pagination info.
1380
+ */
1381
+ getMcpServers(params) {
1382
+ const searchParams = new URLSearchParams();
1383
+ if (params?.limit !== void 0) {
1384
+ searchParams.set("limit", String(params.limit));
1385
+ }
1386
+ if (params?.offset !== void 0) {
1387
+ searchParams.set("offset", String(params.offset));
1388
+ }
1389
+ const queryString = searchParams.toString();
1390
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
1391
+ }
1392
+ /**
1393
+ * Retrieves detailed information for a specific MCP server.
1394
+ * @param serverId - The ID of the MCP server to retrieve.
1395
+ * @param params - Optional parameters, e.g., specific version.
1396
+ * @returns Promise containing the detailed MCP server information.
1397
+ */
1398
+ getMcpServerDetails(serverId, params) {
1399
+ const searchParams = new URLSearchParams();
1400
+ if (params?.version) {
1401
+ searchParams.set("version", params.version);
1402
+ }
1403
+ const queryString = searchParams.toString();
1404
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
1405
+ }
1406
+ /**
1407
+ * Retrieves a list of tools for a specific MCP server.
1408
+ * @param serverId - The ID of the MCP server.
1409
+ * @returns Promise containing the list of tools.
1410
+ */
1411
+ getMcpServerTools(serverId) {
1412
+ return this.request(`/api/mcp/${serverId}/tools`);
1413
+ }
1414
+ /**
1415
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
1416
+ * This instance can then be used to fetch details or execute the tool.
1417
+ * @param serverId - The ID of the MCP server.
1418
+ * @param toolId - The ID of the tool.
1419
+ * @returns MCPTool instance.
1420
+ */
1421
+ getMcpServerTool(serverId, toolId) {
1422
+ return new MCPTool(this.options, serverId, toolId);
1423
+ }
1424
+ /**
1425
+ * Gets an A2A client for interacting with an agent via the A2A protocol
1426
+ * @param agentId - ID of the agent to interact with
1427
+ * @returns A2A client instance
1428
+ */
1429
+ getA2A(agentId) {
1430
+ return new A2A(this.options, agentId);
1431
+ }
485
1432
  };
486
1433
 
487
1434
  export { MastraClient };