@mastra/client-js 0.0.0-message-ordering-20250415215612 → 0.0.0-pass-headers-for-create-mastra-client-20250529190531

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,8 +1,201 @@
1
- import { ZodSchema } from 'zod';
2
- import { zodToJsonSchema } from 'zod-to-json-schema';
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
3
  import { processDataStream } from '@ai-sdk/ui-utils';
4
+ import { ZodSchema } from 'zod';
5
+ import originalZodToJsonSchema from 'zod-to-json-schema';
6
+ import { RuntimeContext } from '@mastra/core/runtime-context';
4
7
 
5
- // 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
+ }
6
199
 
7
200
  // src/resources/base.ts
8
201
  var BaseResource = class {
@@ -22,7 +215,7 @@ var BaseResource = class {
22
215
  let delay = backoffMs;
23
216
  for (let attempt = 0; attempt <= retries; attempt++) {
24
217
  try {
25
- const response = await fetch(`${baseUrl}${path}`, {
218
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
26
219
  ...options,
27
220
  headers: {
28
221
  ...headers,
@@ -62,6 +255,15 @@ var BaseResource = class {
62
255
  throw lastError || new Error("Request failed");
63
256
  }
64
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
+ }
65
267
 
66
268
  // src/resources/agent.ts
67
269
  var AgentVoice = class extends BaseResource {
@@ -133,8 +335,9 @@ var Agent = class extends BaseResource {
133
335
  generate(params) {
134
336
  const processedParams = {
135
337
  ...params,
136
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
137
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_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)
138
341
  };
139
342
  return this.request(`/api/agents/${this.agentId}/generate`, {
140
343
  method: "POST",
@@ -149,8 +352,9 @@ var Agent = class extends BaseResource {
149
352
  async stream(params) {
150
353
  const processedParams = {
151
354
  ...params,
152
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
153
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_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)
154
358
  };
155
359
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
156
360
  method: "POST",
@@ -176,6 +380,22 @@ var Agent = class extends BaseResource {
176
380
  getTool(toolId) {
177
381
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
178
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
+ }
179
399
  /**
180
400
  * Retrieves evaluation results for the agent
181
401
  * @returns Promise containing agent evaluations
@@ -211,8 +431,8 @@ var Network = class extends BaseResource {
211
431
  generate(params) {
212
432
  const processedParams = {
213
433
  ...params,
214
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
215
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
434
+ output: zodToJsonSchema(params.output),
435
+ experimental_output: zodToJsonSchema(params.experimental_output)
216
436
  };
217
437
  return this.request(`/api/networks/${this.networkId}/generate`, {
218
438
  method: "POST",
@@ -227,8 +447,8 @@ var Network = class extends BaseResource {
227
447
  async stream(params) {
228
448
  const processedParams = {
229
449
  ...params,
230
- output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
231
- experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
450
+ output: zodToJsonSchema(params.output),
451
+ experimental_output: zodToJsonSchema(params.experimental_output)
232
452
  };
233
453
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
234
454
  method: "POST",
@@ -284,10 +504,15 @@ var MemoryThread = class extends BaseResource {
284
504
  }
285
505
  /**
286
506
  * Retrieves messages associated with the thread
507
+ * @param params - Optional parameters including limit for number of messages to retrieve
287
508
  * @returns Promise containing thread messages and UI messages
288
509
  */
289
- getMessages() {
290
- 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()}`);
291
516
  }
292
517
  };
293
518
 
@@ -357,34 +582,50 @@ var Vector = class extends BaseResource {
357
582
  }
358
583
  };
359
584
 
360
- // src/resources/workflow.ts
585
+ // src/resources/legacy-workflow.ts
361
586
  var RECORD_SEPARATOR = "";
362
- var Workflow = class extends BaseResource {
587
+ var LegacyWorkflow = class extends BaseResource {
363
588
  constructor(options, workflowId) {
364
589
  super(options);
365
590
  this.workflowId = workflowId;
366
591
  }
367
592
  /**
368
- * Retrieves details about the workflow
369
- * @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
370
595
  */
371
596
  details() {
372
- return this.request(`/api/workflows/${this.workflowId}`);
597
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
373
598
  }
374
599
  /**
375
- * @deprecated Use `startAsync` instead
376
- * Executes the workflow with the provided parameters
377
- * @param params - Parameters required for workflow execution
378
- * @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
379
603
  */
380
- execute(params) {
381
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
382
- method: "POST",
383
- body: params
384
- });
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
+ }
385
626
  }
386
627
  /**
387
- * Creates a new workflow run
628
+ * Creates a new legacy workflow run
388
629
  * @returns Promise containing the generated run ID
389
630
  */
390
631
  createRun(params) {
@@ -392,34 +633,34 @@ var Workflow = class extends BaseResource {
392
633
  if (!!params?.runId) {
393
634
  searchParams.set("runId", params.runId);
394
635
  }
395
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
636
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
396
637
  method: "POST"
397
638
  });
398
639
  }
399
640
  /**
400
- * Starts a workflow run synchronously without waiting for the workflow to complete
641
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
401
642
  * @param params - Object containing the runId and triggerData
402
643
  * @returns Promise containing success message
403
644
  */
404
645
  start(params) {
405
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
646
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
406
647
  method: "POST",
407
648
  body: params?.triggerData
408
649
  });
409
650
  }
410
651
  /**
411
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
652
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
412
653
  * @param stepId - ID of the step to resume
413
- * @param runId - ID of the workflow run
414
- * @param context - Context to resume the workflow with
415
- * @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
416
657
  */
417
658
  resume({
418
659
  stepId,
419
660
  runId,
420
661
  context
421
662
  }) {
422
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
663
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
423
664
  method: "POST",
424
665
  body: {
425
666
  stepId,
@@ -437,18 +678,18 @@ var Workflow = class extends BaseResource {
437
678
  if (!!params?.runId) {
438
679
  searchParams.set("runId", params.runId);
439
680
  }
440
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
681
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
441
682
  method: "POST",
442
683
  body: params?.triggerData
443
684
  });
444
685
  }
445
686
  /**
446
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
687
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
447
688
  * @param params - Object containing the runId, stepId, and context
448
689
  * @returns Promise containing the workflow resume results
449
690
  */
450
691
  resumeAsync(params) {
451
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
692
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
452
693
  method: "POST",
453
694
  body: {
454
695
  stepId: params.stepId,
@@ -487,7 +728,7 @@ var Workflow = class extends BaseResource {
487
728
  }
488
729
  }
489
730
  }
490
- } catch (error) {
731
+ } catch {
491
732
  }
492
733
  }
493
734
  if (buffer) {
@@ -502,16 +743,16 @@ var Workflow = class extends BaseResource {
502
743
  }
503
744
  }
504
745
  /**
505
- * Watches workflow transitions in real-time
746
+ * Watches legacy workflow transitions in real-time
506
747
  * @param runId - Optional run ID to filter the watch stream
507
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
748
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
508
749
  */
509
750
  async watch({ runId }, onRecord) {
510
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
751
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
511
752
  stream: true
512
753
  });
513
754
  if (!response.ok) {
514
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
755
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
515
756
  }
516
757
  if (!response.body) {
517
758
  throw new Error("Response body is null");
@@ -541,9 +782,387 @@ var Tool = class extends BaseResource {
541
782
  * @returns Promise containing the tool execution results
542
783
  */
543
784
  execute(params) {
544
- 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()}`, {
545
794
  method: "POST",
546
- 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
+ if (typeof record === "string") {
1031
+ onRecord(JSON.parse(record));
1032
+ } else {
1033
+ onRecord(record);
1034
+ }
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1039
+ * serializing each as JSON and separating them with the record separator (\x1E).
1040
+ *
1041
+ * @param records - An iterable or async iterable of objects to stream
1042
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1043
+ */
1044
+ static createRecordStream(records) {
1045
+ const encoder = new TextEncoder();
1046
+ return new ReadableStream({
1047
+ async start(controller) {
1048
+ try {
1049
+ for await (const record of records) {
1050
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1051
+ controller.enqueue(encoder.encode(json));
1052
+ }
1053
+ controller.close();
1054
+ } catch (err) {
1055
+ controller.error(err);
1056
+ }
1057
+ }
1058
+ });
1059
+ }
1060
+ };
1061
+
1062
+ // src/resources/a2a.ts
1063
+ var A2A = class extends BaseResource {
1064
+ constructor(options, agentId) {
1065
+ super(options);
1066
+ this.agentId = agentId;
1067
+ }
1068
+ /**
1069
+ * Get the agent card with metadata about the agent
1070
+ * @returns Promise containing the agent card information
1071
+ */
1072
+ async getCard() {
1073
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1074
+ }
1075
+ /**
1076
+ * Send a message to the agent and get a response
1077
+ * @param params - Parameters for the task
1078
+ * @returns Promise containing the task response
1079
+ */
1080
+ async sendMessage(params) {
1081
+ const response = await this.request(`/a2a/${this.agentId}`, {
1082
+ method: "POST",
1083
+ body: {
1084
+ method: "tasks/send",
1085
+ params
1086
+ }
1087
+ });
1088
+ return { task: response.result };
1089
+ }
1090
+ /**
1091
+ * Get the status and result of a task
1092
+ * @param params - Parameters for querying the task
1093
+ * @returns Promise containing the task response
1094
+ */
1095
+ async getTask(params) {
1096
+ const response = await this.request(`/a2a/${this.agentId}`, {
1097
+ method: "POST",
1098
+ body: {
1099
+ method: "tasks/get",
1100
+ params
1101
+ }
1102
+ });
1103
+ return response.result;
1104
+ }
1105
+ /**
1106
+ * Cancel a running task
1107
+ * @param params - Parameters identifying the task to cancel
1108
+ * @returns Promise containing the task response
1109
+ */
1110
+ async cancelTask(params) {
1111
+ return this.request(`/a2a/${this.agentId}`, {
1112
+ method: "POST",
1113
+ body: {
1114
+ method: "tasks/cancel",
1115
+ params
1116
+ }
1117
+ });
1118
+ }
1119
+ /**
1120
+ * Send a message and subscribe to streaming updates (not fully implemented)
1121
+ * @param params - Parameters for the task
1122
+ * @returns Promise containing the task response
1123
+ */
1124
+ async sendAndSubscribe(params) {
1125
+ return this.request(`/a2a/${this.agentId}`, {
1126
+ method: "POST",
1127
+ body: {
1128
+ method: "tasks/sendSubscribe",
1129
+ params
1130
+ },
1131
+ stream: true
1132
+ });
1133
+ }
1134
+ };
1135
+
1136
+ // src/resources/mcp-tool.ts
1137
+ var MCPTool = class extends BaseResource {
1138
+ serverId;
1139
+ toolId;
1140
+ constructor(options, serverId, toolId) {
1141
+ super(options);
1142
+ this.serverId = serverId;
1143
+ this.toolId = toolId;
1144
+ }
1145
+ /**
1146
+ * Retrieves details about this specific tool from the MCP server.
1147
+ * @returns Promise containing the tool's information (name, description, schema).
1148
+ */
1149
+ details() {
1150
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1151
+ }
1152
+ /**
1153
+ * Executes this specific tool on the MCP server.
1154
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1155
+ * @returns Promise containing the result of the tool execution.
1156
+ */
1157
+ execute(params) {
1158
+ const body = {};
1159
+ if (params.data !== void 0) body.data = params.data;
1160
+ if (params.runtimeContext !== void 0) {
1161
+ body.runtimeContext = params.runtimeContext;
1162
+ }
1163
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1164
+ method: "POST",
1165
+ body: Object.keys(body).length > 0 ? body : void 0
547
1166
  });
548
1167
  }
549
1168
  };
@@ -560,6 +1179,21 @@ var MastraClient = class extends BaseResource {
560
1179
  getAgents() {
561
1180
  return this.request("/api/agents");
562
1181
  }
1182
+ async getAGUI({ resourceId }) {
1183
+ const agents = await this.getAgents();
1184
+ return Object.entries(agents).reduce(
1185
+ (acc, [agentId]) => {
1186
+ const agent = this.getAgent(agentId);
1187
+ acc[agentId] = new AGUIAdapter({
1188
+ agentId,
1189
+ agent,
1190
+ resourceId
1191
+ });
1192
+ return acc;
1193
+ },
1194
+ {}
1195
+ );
1196
+ }
563
1197
  /**
564
1198
  * Gets an agent instance by ID
565
1199
  * @param agentId - ID of the agent to retrieve
@@ -625,6 +1259,21 @@ var MastraClient = class extends BaseResource {
625
1259
  getTool(toolId) {
626
1260
  return new Tool(this.options, toolId);
627
1261
  }
1262
+ /**
1263
+ * Retrieves all available legacy workflows
1264
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1265
+ */
1266
+ getLegacyWorkflows() {
1267
+ return this.request("/api/workflows/legacy");
1268
+ }
1269
+ /**
1270
+ * Gets a legacy workflow instance by ID
1271
+ * @param workflowId - ID of the legacy workflow to retrieve
1272
+ * @returns Legacy Workflow instance
1273
+ */
1274
+ getLegacyWorkflow(workflowId) {
1275
+ return new LegacyWorkflow(this.options, workflowId);
1276
+ }
628
1277
  /**
629
1278
  * Retrieves all available workflows
630
1279
  * @returns Promise containing map of workflow IDs to workflow details
@@ -677,7 +1326,7 @@ var MastraClient = class extends BaseResource {
677
1326
  * @returns Promise containing telemetry data
678
1327
  */
679
1328
  getTelemetry(params) {
680
- const { name, scope, page, perPage, attribute } = params || {};
1329
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
681
1330
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
682
1331
  const searchParams = new URLSearchParams();
683
1332
  if (name) {
@@ -701,6 +1350,12 @@ var MastraClient = class extends BaseResource {
701
1350
  searchParams.set("attribute", _attribute);
702
1351
  }
703
1352
  }
1353
+ if (fromDate) {
1354
+ searchParams.set("fromDate", fromDate.toISOString());
1355
+ }
1356
+ if (toDate) {
1357
+ searchParams.set("toDate", toDate.toISOString());
1358
+ }
704
1359
  if (searchParams.size) {
705
1360
  return this.request(`/api/telemetry?${searchParams}`);
706
1361
  } else {
@@ -722,6 +1377,62 @@ var MastraClient = class extends BaseResource {
722
1377
  getNetwork(networkId) {
723
1378
  return new Network(this.options, networkId);
724
1379
  }
1380
+ /**
1381
+ * Retrieves a list of available MCP servers.
1382
+ * @param params - Optional parameters for pagination (limit, offset).
1383
+ * @returns Promise containing the list of MCP servers and pagination info.
1384
+ */
1385
+ getMcpServers(params) {
1386
+ const searchParams = new URLSearchParams();
1387
+ if (params?.limit !== void 0) {
1388
+ searchParams.set("limit", String(params.limit));
1389
+ }
1390
+ if (params?.offset !== void 0) {
1391
+ searchParams.set("offset", String(params.offset));
1392
+ }
1393
+ const queryString = searchParams.toString();
1394
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
1395
+ }
1396
+ /**
1397
+ * Retrieves detailed information for a specific MCP server.
1398
+ * @param serverId - The ID of the MCP server to retrieve.
1399
+ * @param params - Optional parameters, e.g., specific version.
1400
+ * @returns Promise containing the detailed MCP server information.
1401
+ */
1402
+ getMcpServerDetails(serverId, params) {
1403
+ const searchParams = new URLSearchParams();
1404
+ if (params?.version) {
1405
+ searchParams.set("version", params.version);
1406
+ }
1407
+ const queryString = searchParams.toString();
1408
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
1409
+ }
1410
+ /**
1411
+ * Retrieves a list of tools for a specific MCP server.
1412
+ * @param serverId - The ID of the MCP server.
1413
+ * @returns Promise containing the list of tools.
1414
+ */
1415
+ getMcpServerTools(serverId) {
1416
+ return this.request(`/api/mcp/${serverId}/tools`);
1417
+ }
1418
+ /**
1419
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
1420
+ * This instance can then be used to fetch details or execute the tool.
1421
+ * @param serverId - The ID of the MCP server.
1422
+ * @param toolId - The ID of the tool.
1423
+ * @returns MCPTool instance.
1424
+ */
1425
+ getMcpServerTool(serverId, toolId) {
1426
+ return new MCPTool(this.options, serverId, toolId);
1427
+ }
1428
+ /**
1429
+ * Gets an A2A client for interacting with an agent via the A2A protocol
1430
+ * @param agentId - ID of the agent to interact with
1431
+ * @returns A2A client instance
1432
+ */
1433
+ getA2A(agentId) {
1434
+ return new A2A(this.options, agentId);
1435
+ }
725
1436
  };
726
1437
 
727
1438
  export { MastraClient };