@mastra/client-js 0.0.0-vnextWorkflows-20250422142014 → 0.0.0-workflow-deno-20250616115451

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 CHANGED
@@ -1,10 +1,235 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
- var zodToJsonSchema = require('zod-to-json-schema');
3
+ var client = require('@ag-ui/client');
4
+ var rxjs = require('rxjs');
5
5
  var uiUtils = require('@ai-sdk/ui-utils');
6
+ var zod = require('zod');
7
+ var originalZodToJsonSchema = require('zod-to-json-schema');
8
+ var tools = require('@mastra/core/tools');
9
+ var runtimeContext = require('@mastra/core/runtime-context');
6
10
 
7
- // src/resources/agent.ts
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var originalZodToJsonSchema__default = /*#__PURE__*/_interopDefault(originalZodToJsonSchema);
14
+
15
+ // src/adapters/agui.ts
16
+ var AGUIAdapter = class extends client.AbstractAgent {
17
+ agent;
18
+ resourceId;
19
+ constructor({ agent, agentId, resourceId, ...rest }) {
20
+ super({
21
+ agentId,
22
+ ...rest
23
+ });
24
+ this.agent = agent;
25
+ this.resourceId = resourceId;
26
+ }
27
+ run(input) {
28
+ return new rxjs.Observable((subscriber) => {
29
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
30
+ subscriber.next({
31
+ type: client.EventType.RUN_STARTED,
32
+ threadId: input.threadId,
33
+ runId: input.runId
34
+ });
35
+ this.agent.stream({
36
+ threadId: input.threadId,
37
+ resourceId: this.resourceId ?? "",
38
+ runId: input.runId,
39
+ messages: convertedMessages,
40
+ clientTools: input.tools.reduce(
41
+ (acc, tool) => {
42
+ acc[tool.name] = {
43
+ id: tool.name,
44
+ description: tool.description,
45
+ inputSchema: tool.parameters
46
+ };
47
+ return acc;
48
+ },
49
+ {}
50
+ )
51
+ }).then((response) => {
52
+ let currentMessageId = void 0;
53
+ let isInTextMessage = false;
54
+ return response.processDataStream({
55
+ onTextPart: (text) => {
56
+ if (currentMessageId === void 0) {
57
+ currentMessageId = generateUUID();
58
+ const message2 = {
59
+ type: client.EventType.TEXT_MESSAGE_START,
60
+ messageId: currentMessageId,
61
+ role: "assistant"
62
+ };
63
+ subscriber.next(message2);
64
+ isInTextMessage = true;
65
+ }
66
+ const message = {
67
+ type: client.EventType.TEXT_MESSAGE_CONTENT,
68
+ messageId: currentMessageId,
69
+ delta: text
70
+ };
71
+ subscriber.next(message);
72
+ },
73
+ onFinishMessagePart: () => {
74
+ if (currentMessageId !== void 0) {
75
+ const message = {
76
+ type: client.EventType.TEXT_MESSAGE_END,
77
+ messageId: currentMessageId
78
+ };
79
+ subscriber.next(message);
80
+ isInTextMessage = false;
81
+ }
82
+ subscriber.next({
83
+ type: client.EventType.RUN_FINISHED,
84
+ threadId: input.threadId,
85
+ runId: input.runId
86
+ });
87
+ subscriber.complete();
88
+ },
89
+ onToolCallPart(streamPart) {
90
+ const parentMessageId = currentMessageId || generateUUID();
91
+ if (isInTextMessage) {
92
+ const message = {
93
+ type: client.EventType.TEXT_MESSAGE_END,
94
+ messageId: parentMessageId
95
+ };
96
+ subscriber.next(message);
97
+ isInTextMessage = false;
98
+ }
99
+ subscriber.next({
100
+ type: client.EventType.TOOL_CALL_START,
101
+ toolCallId: streamPart.toolCallId,
102
+ toolCallName: streamPart.toolName,
103
+ parentMessageId
104
+ });
105
+ subscriber.next({
106
+ type: client.EventType.TOOL_CALL_ARGS,
107
+ toolCallId: streamPart.toolCallId,
108
+ delta: JSON.stringify(streamPart.args),
109
+ parentMessageId
110
+ });
111
+ subscriber.next({
112
+ type: client.EventType.TOOL_CALL_END,
113
+ toolCallId: streamPart.toolCallId,
114
+ parentMessageId
115
+ });
116
+ }
117
+ });
118
+ }).catch((error) => {
119
+ console.error("error", error);
120
+ subscriber.error(error);
121
+ });
122
+ return () => {
123
+ };
124
+ });
125
+ }
126
+ };
127
+ function generateUUID() {
128
+ if (typeof crypto !== "undefined") {
129
+ if (typeof crypto.randomUUID === "function") {
130
+ return crypto.randomUUID();
131
+ }
132
+ if (typeof crypto.getRandomValues === "function") {
133
+ const buffer = new Uint8Array(16);
134
+ crypto.getRandomValues(buffer);
135
+ buffer[6] = buffer[6] & 15 | 64;
136
+ buffer[8] = buffer[8] & 63 | 128;
137
+ let hex = "";
138
+ for (let i = 0; i < 16; i++) {
139
+ hex += buffer[i].toString(16).padStart(2, "0");
140
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
141
+ }
142
+ return hex;
143
+ }
144
+ }
145
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
146
+ const r = Math.random() * 16 | 0;
147
+ const v = c === "x" ? r : r & 3 | 8;
148
+ return v.toString(16);
149
+ });
150
+ }
151
+ function convertMessagesToMastraMessages(messages) {
152
+ const result = [];
153
+ for (const message of messages) {
154
+ if (message.role === "assistant") {
155
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
156
+ for (const toolCall of message.toolCalls ?? []) {
157
+ parts.push({
158
+ type: "tool-call",
159
+ toolCallId: toolCall.id,
160
+ toolName: toolCall.function.name,
161
+ args: JSON.parse(toolCall.function.arguments)
162
+ });
163
+ }
164
+ result.push({
165
+ role: "assistant",
166
+ content: parts
167
+ });
168
+ if (message.toolCalls?.length) {
169
+ result.push({
170
+ role: "tool",
171
+ content: message.toolCalls.map((toolCall) => ({
172
+ type: "tool-result",
173
+ toolCallId: toolCall.id,
174
+ toolName: toolCall.function.name,
175
+ result: JSON.parse(toolCall.function.arguments)
176
+ }))
177
+ });
178
+ }
179
+ } else if (message.role === "user") {
180
+ result.push({
181
+ role: "user",
182
+ content: message.content || ""
183
+ });
184
+ } else if (message.role === "tool") {
185
+ result.push({
186
+ role: "tool",
187
+ content: [
188
+ {
189
+ type: "tool-result",
190
+ toolCallId: message.toolCallId,
191
+ toolName: "unknown",
192
+ result: message.content
193
+ }
194
+ ]
195
+ });
196
+ }
197
+ }
198
+ return result;
199
+ }
200
+ function zodToJsonSchema(zodSchema) {
201
+ if (!(zodSchema instanceof zod.ZodSchema)) {
202
+ return zodSchema;
203
+ }
204
+ return originalZodToJsonSchema__default.default(zodSchema, { $refStrategy: "none" });
205
+ }
206
+ function processClientTools(clientTools) {
207
+ if (!clientTools) {
208
+ return void 0;
209
+ }
210
+ return Object.fromEntries(
211
+ Object.entries(clientTools).map(([key, value]) => {
212
+ if (tools.isVercelTool(value)) {
213
+ return [
214
+ key,
215
+ {
216
+ ...value,
217
+ parameters: value.parameters ? zodToJsonSchema(value.parameters) : void 0
218
+ }
219
+ ];
220
+ } else {
221
+ return [
222
+ key,
223
+ {
224
+ ...value,
225
+ inputSchema: value.inputSchema ? zodToJsonSchema(value.inputSchema) : void 0,
226
+ outputSchema: value.outputSchema ? zodToJsonSchema(value.outputSchema) : void 0
227
+ }
228
+ ];
229
+ }
230
+ })
231
+ );
232
+ }
8
233
 
9
234
  // src/resources/base.ts
10
235
  var BaseResource = class {
@@ -24,7 +249,7 @@ var BaseResource = class {
24
249
  let delay = backoffMs;
25
250
  for (let attempt = 0; attempt <= retries; attempt++) {
26
251
  try {
27
- const response = await fetch(`${baseUrl}${path}`, {
252
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, {
28
253
  ...options,
29
254
  headers: {
30
255
  ...headers,
@@ -64,6 +289,15 @@ var BaseResource = class {
64
289
  throw lastError || new Error("Request failed");
65
290
  }
66
291
  };
292
+ function parseClientRuntimeContext(runtimeContext$1) {
293
+ if (runtimeContext$1) {
294
+ if (runtimeContext$1 instanceof runtimeContext.RuntimeContext) {
295
+ return Object.fromEntries(runtimeContext$1.entries());
296
+ }
297
+ return runtimeContext$1;
298
+ }
299
+ return void 0;
300
+ }
67
301
 
68
302
  // src/resources/agent.ts
69
303
  var AgentVoice = class extends BaseResource {
@@ -112,6 +346,13 @@ var AgentVoice = class extends BaseResource {
112
346
  getSpeakers() {
113
347
  return this.request(`/api/agents/${this.agentId}/voice/speakers`);
114
348
  }
349
+ /**
350
+ * Get the listener configuration for the agent's voice provider
351
+ * @returns Promise containing a check if the agent has listening capabilities
352
+ */
353
+ getListener() {
354
+ return this.request(`/api/agents/${this.agentId}/voice/listener`);
355
+ }
115
356
  };
116
357
  var Agent = class extends BaseResource {
117
358
  constructor(options, agentId) {
@@ -127,16 +368,13 @@ var Agent = class extends BaseResource {
127
368
  details() {
128
369
  return this.request(`/api/agents/${this.agentId}`);
129
370
  }
130
- /**
131
- * Generates a response from the agent
132
- * @param params - Generation parameters including prompt
133
- * @returns Promise containing the generated response
134
- */
135
371
  generate(params) {
136
372
  const processedParams = {
137
373
  ...params,
138
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
139
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
374
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
375
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
376
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
377
+ clientTools: processClientTools(params.clientTools)
140
378
  };
141
379
  return this.request(`/api/agents/${this.agentId}/generate`, {
142
380
  method: "POST",
@@ -151,8 +389,10 @@ var Agent = class extends BaseResource {
151
389
  async stream(params) {
152
390
  const processedParams = {
153
391
  ...params,
154
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
155
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
392
+ output: params.output ? zodToJsonSchema(params.output) : void 0,
393
+ experimental_output: params.experimental_output ? zodToJsonSchema(params.experimental_output) : void 0,
394
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext),
395
+ clientTools: processClientTools(params.clientTools)
156
396
  };
157
397
  const response = await this.request(`/api/agents/${this.agentId}/stream`, {
158
398
  method: "POST",
@@ -178,6 +418,22 @@ var Agent = class extends BaseResource {
178
418
  getTool(toolId) {
179
419
  return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
180
420
  }
421
+ /**
422
+ * Executes a tool for the agent
423
+ * @param toolId - ID of the tool to execute
424
+ * @param params - Parameters required for tool execution
425
+ * @returns Promise containing the tool execution results
426
+ */
427
+ executeTool(toolId, params) {
428
+ const body = {
429
+ data: params.data,
430
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0
431
+ };
432
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}/execute`, {
433
+ method: "POST",
434
+ body
435
+ });
436
+ }
181
437
  /**
182
438
  * Retrieves evaluation results for the agent
183
439
  * @returns Promise containing agent evaluations
@@ -213,8 +469,8 @@ var Network = class extends BaseResource {
213
469
  generate(params) {
214
470
  const processedParams = {
215
471
  ...params,
216
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
217
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
472
+ output: zodToJsonSchema(params.output),
473
+ experimental_output: zodToJsonSchema(params.experimental_output)
218
474
  };
219
475
  return this.request(`/api/networks/${this.networkId}/generate`, {
220
476
  method: "POST",
@@ -229,8 +485,8 @@ var Network = class extends BaseResource {
229
485
  async stream(params) {
230
486
  const processedParams = {
231
487
  ...params,
232
- output: params.output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.output) : params.output,
233
- experimental_output: params.experimental_output instanceof zod.ZodSchema ? zodToJsonSchema.zodToJsonSchema(params.experimental_output) : params.experimental_output
488
+ output: zodToJsonSchema(params.output),
489
+ experimental_output: zodToJsonSchema(params.experimental_output)
234
490
  };
235
491
  const response = await this.request(`/api/networks/${this.networkId}/stream`, {
236
492
  method: "POST",
@@ -286,10 +542,15 @@ var MemoryThread = class extends BaseResource {
286
542
  }
287
543
  /**
288
544
  * Retrieves messages associated with the thread
545
+ * @param params - Optional parameters including limit for number of messages to retrieve
289
546
  * @returns Promise containing thread messages and UI messages
290
547
  */
291
- getMessages() {
292
- return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
548
+ getMessages(params) {
549
+ const query = new URLSearchParams({
550
+ agentId: this.agentId,
551
+ ...params?.limit ? { limit: params.limit.toString() } : {}
552
+ });
553
+ return this.request(`/api/memory/threads/${this.threadId}/messages?${query.toString()}`);
293
554
  }
294
555
  };
295
556
 
@@ -359,34 +620,50 @@ var Vector = class extends BaseResource {
359
620
  }
360
621
  };
361
622
 
362
- // src/resources/workflow.ts
623
+ // src/resources/legacy-workflow.ts
363
624
  var RECORD_SEPARATOR = "";
364
- var Workflow = class extends BaseResource {
625
+ var LegacyWorkflow = class extends BaseResource {
365
626
  constructor(options, workflowId) {
366
627
  super(options);
367
628
  this.workflowId = workflowId;
368
629
  }
369
630
  /**
370
- * Retrieves details about the workflow
371
- * @returns Promise containing workflow details including steps and graphs
631
+ * Retrieves details about the legacy workflow
632
+ * @returns Promise containing legacy workflow details including steps and graphs
372
633
  */
373
634
  details() {
374
- return this.request(`/api/workflows/${this.workflowId}`);
635
+ return this.request(`/api/workflows/legacy/${this.workflowId}`);
375
636
  }
376
637
  /**
377
- * @deprecated Use `startAsync` instead
378
- * Executes the workflow with the provided parameters
379
- * @param params - Parameters required for workflow execution
380
- * @returns Promise containing the workflow execution results
638
+ * Retrieves all runs for a legacy workflow
639
+ * @param params - Parameters for filtering runs
640
+ * @returns Promise containing legacy workflow runs array
381
641
  */
382
- execute(params) {
383
- return this.request(`/api/workflows/${this.workflowId}/execute`, {
384
- method: "POST",
385
- body: params
386
- });
642
+ runs(params) {
643
+ const searchParams = new URLSearchParams();
644
+ if (params?.fromDate) {
645
+ searchParams.set("fromDate", params.fromDate.toISOString());
646
+ }
647
+ if (params?.toDate) {
648
+ searchParams.set("toDate", params.toDate.toISOString());
649
+ }
650
+ if (params?.limit) {
651
+ searchParams.set("limit", String(params.limit));
652
+ }
653
+ if (params?.offset) {
654
+ searchParams.set("offset", String(params.offset));
655
+ }
656
+ if (params?.resourceId) {
657
+ searchParams.set("resourceId", params.resourceId);
658
+ }
659
+ if (searchParams.size) {
660
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs?${searchParams}`);
661
+ } else {
662
+ return this.request(`/api/workflows/legacy/${this.workflowId}/runs`);
663
+ }
387
664
  }
388
665
  /**
389
- * Creates a new workflow run
666
+ * Creates a new legacy workflow run
390
667
  * @returns Promise containing the generated run ID
391
668
  */
392
669
  createRun(params) {
@@ -394,34 +671,34 @@ var Workflow = class extends BaseResource {
394
671
  if (!!params?.runId) {
395
672
  searchParams.set("runId", params.runId);
396
673
  }
397
- return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
674
+ return this.request(`/api/workflows/legacy/${this.workflowId}/create-run?${searchParams.toString()}`, {
398
675
  method: "POST"
399
676
  });
400
677
  }
401
678
  /**
402
- * Starts a workflow run synchronously without waiting for the workflow to complete
679
+ * Starts a legacy workflow run synchronously without waiting for the workflow to complete
403
680
  * @param params - Object containing the runId and triggerData
404
681
  * @returns Promise containing success message
405
682
  */
406
683
  start(params) {
407
- return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
684
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start?runId=${params.runId}`, {
408
685
  method: "POST",
409
686
  body: params?.triggerData
410
687
  });
411
688
  }
412
689
  /**
413
- * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
690
+ * Resumes a suspended legacy workflow step synchronously without waiting for the workflow to complete
414
691
  * @param stepId - ID of the step to resume
415
- * @param runId - ID of the workflow run
416
- * @param context - Context to resume the workflow with
417
- * @returns Promise containing the workflow resume results
692
+ * @param runId - ID of the legacy workflow run
693
+ * @param context - Context to resume the legacy workflow with
694
+ * @returns Promise containing the legacy workflow resume results
418
695
  */
419
696
  resume({
420
697
  stepId,
421
698
  runId,
422
699
  context
423
700
  }) {
424
- return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
701
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume?runId=${runId}`, {
425
702
  method: "POST",
426
703
  body: {
427
704
  stepId,
@@ -439,18 +716,18 @@ var Workflow = class extends BaseResource {
439
716
  if (!!params?.runId) {
440
717
  searchParams.set("runId", params.runId);
441
718
  }
442
- return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
719
+ return this.request(`/api/workflows/legacy/${this.workflowId}/start-async?${searchParams.toString()}`, {
443
720
  method: "POST",
444
721
  body: params?.triggerData
445
722
  });
446
723
  }
447
724
  /**
448
- * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
725
+ * Resumes a suspended legacy workflow step asynchronously and returns a promise that resolves when the workflow is complete
449
726
  * @param params - Object containing the runId, stepId, and context
450
727
  * @returns Promise containing the workflow resume results
451
728
  */
452
729
  resumeAsync(params) {
453
- return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
730
+ return this.request(`/api/workflows/legacy/${this.workflowId}/resume-async?runId=${params.runId}`, {
454
731
  method: "POST",
455
732
  body: {
456
733
  stepId: params.stepId,
@@ -489,7 +766,7 @@ var Workflow = class extends BaseResource {
489
766
  }
490
767
  }
491
768
  }
492
- } catch (error) {
769
+ } catch {
493
770
  }
494
771
  }
495
772
  if (buffer) {
@@ -504,16 +781,16 @@ var Workflow = class extends BaseResource {
504
781
  }
505
782
  }
506
783
  /**
507
- * Watches workflow transitions in real-time
784
+ * Watches legacy workflow transitions in real-time
508
785
  * @param runId - Optional run ID to filter the watch stream
509
- * @returns AsyncGenerator that yields parsed records from the workflow watch stream
786
+ * @returns AsyncGenerator that yields parsed records from the legacy workflow watch stream
510
787
  */
511
788
  async watch({ runId }, onRecord) {
512
- const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
789
+ const response = await this.request(`/api/workflows/legacy/${this.workflowId}/watch?runId=${runId}`, {
513
790
  stream: true
514
791
  });
515
792
  if (!response.ok) {
516
- throw new Error(`Failed to watch workflow: ${response.statusText}`);
793
+ throw new Error(`Failed to watch legacy workflow: ${response.statusText}`);
517
794
  }
518
795
  if (!response.body) {
519
796
  throw new Error("Response body is null");
@@ -543,9 +820,403 @@ var Tool = class extends BaseResource {
543
820
  * @returns Promise containing the tool execution results
544
821
  */
545
822
  execute(params) {
546
- return this.request(`/api/tools/${this.toolId}/execute`, {
823
+ const url = new URLSearchParams();
824
+ if (params.runId) {
825
+ url.set("runId", params.runId);
826
+ }
827
+ const body = {
828
+ data: params.data,
829
+ runtimeContext: parseClientRuntimeContext(params.runtimeContext)
830
+ };
831
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
547
832
  method: "POST",
548
- body: params
833
+ body
834
+ });
835
+ }
836
+ };
837
+
838
+ // src/resources/workflow.ts
839
+ var RECORD_SEPARATOR2 = "";
840
+ var Workflow = class extends BaseResource {
841
+ constructor(options, workflowId) {
842
+ super(options);
843
+ this.workflowId = workflowId;
844
+ }
845
+ /**
846
+ * Creates an async generator that processes a readable stream and yields workflow records
847
+ * separated by the Record Separator character (\x1E)
848
+ *
849
+ * @param stream - The readable stream to process
850
+ * @returns An async generator that yields parsed records
851
+ */
852
+ async *streamProcessor(stream) {
853
+ const reader = stream.getReader();
854
+ let doneReading = false;
855
+ let buffer = "";
856
+ try {
857
+ while (!doneReading) {
858
+ const { done, value } = await reader.read();
859
+ doneReading = done;
860
+ if (done && !value) continue;
861
+ try {
862
+ const decoded = value ? new TextDecoder().decode(value) : "";
863
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
864
+ buffer = chunks.pop() || "";
865
+ for (const chunk of chunks) {
866
+ if (chunk) {
867
+ if (typeof chunk === "string") {
868
+ try {
869
+ const parsedChunk = JSON.parse(chunk);
870
+ yield parsedChunk;
871
+ } catch {
872
+ }
873
+ }
874
+ }
875
+ }
876
+ } catch {
877
+ }
878
+ }
879
+ if (buffer) {
880
+ try {
881
+ yield JSON.parse(buffer);
882
+ } catch {
883
+ }
884
+ }
885
+ } finally {
886
+ reader.cancel().catch(() => {
887
+ });
888
+ }
889
+ }
890
+ /**
891
+ * Retrieves details about the workflow
892
+ * @returns Promise containing workflow details including steps and graphs
893
+ */
894
+ details() {
895
+ return this.request(`/api/workflows/${this.workflowId}`);
896
+ }
897
+ /**
898
+ * Retrieves all runs for a workflow
899
+ * @param params - Parameters for filtering runs
900
+ * @returns Promise containing workflow runs array
901
+ */
902
+ runs(params) {
903
+ const searchParams = new URLSearchParams();
904
+ if (params?.fromDate) {
905
+ searchParams.set("fromDate", params.fromDate.toISOString());
906
+ }
907
+ if (params?.toDate) {
908
+ searchParams.set("toDate", params.toDate.toISOString());
909
+ }
910
+ if (params?.limit) {
911
+ searchParams.set("limit", String(params.limit));
912
+ }
913
+ if (params?.offset) {
914
+ searchParams.set("offset", String(params.offset));
915
+ }
916
+ if (params?.resourceId) {
917
+ searchParams.set("resourceId", params.resourceId);
918
+ }
919
+ if (searchParams.size) {
920
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
921
+ } else {
922
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
923
+ }
924
+ }
925
+ /**
926
+ * Retrieves a specific workflow run by its ID
927
+ * @param runId - The ID of the workflow run to retrieve
928
+ * @returns Promise containing the workflow run details
929
+ */
930
+ runById(runId) {
931
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}`);
932
+ }
933
+ /**
934
+ * Retrieves the execution result for a specific workflow run by its ID
935
+ * @param runId - The ID of the workflow run to retrieve the execution result for
936
+ * @returns Promise containing the workflow run execution result
937
+ */
938
+ runExecutionResult(runId) {
939
+ return this.request(`/api/workflows/${this.workflowId}/runs/${runId}/execution-result`);
940
+ }
941
+ /**
942
+ * Creates a new workflow run
943
+ * @param params - Optional object containing the optional runId
944
+ * @returns Promise containing the runId of the created run
945
+ */
946
+ createRun(params) {
947
+ const searchParams = new URLSearchParams();
948
+ if (!!params?.runId) {
949
+ searchParams.set("runId", params.runId);
950
+ }
951
+ return this.request(`/api/workflows/${this.workflowId}/create-run?${searchParams.toString()}`, {
952
+ method: "POST"
953
+ });
954
+ }
955
+ /**
956
+ * Starts a workflow run synchronously without waiting for the workflow to complete
957
+ * @param params - Object containing the runId, inputData and runtimeContext
958
+ * @returns Promise containing success message
959
+ */
960
+ start(params) {
961
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
962
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
963
+ method: "POST",
964
+ body: { inputData: params?.inputData, runtimeContext }
965
+ });
966
+ }
967
+ /**
968
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
969
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
970
+ * @returns Promise containing success message
971
+ */
972
+ resume({
973
+ step,
974
+ runId,
975
+ resumeData,
976
+ ...rest
977
+ }) {
978
+ const runtimeContext = parseClientRuntimeContext(rest.runtimeContext);
979
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
980
+ method: "POST",
981
+ stream: true,
982
+ body: {
983
+ step,
984
+ resumeData,
985
+ runtimeContext
986
+ }
987
+ });
988
+ }
989
+ /**
990
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
991
+ * @param params - Object containing the optional runId, inputData and runtimeContext
992
+ * @returns Promise containing the workflow execution results
993
+ */
994
+ startAsync(params) {
995
+ const searchParams = new URLSearchParams();
996
+ if (!!params?.runId) {
997
+ searchParams.set("runId", params.runId);
998
+ }
999
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1000
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
1001
+ method: "POST",
1002
+ body: { inputData: params.inputData, runtimeContext }
1003
+ });
1004
+ }
1005
+ /**
1006
+ * Starts a vNext workflow run and returns a stream
1007
+ * @param params - Object containing the optional runId, inputData and runtimeContext
1008
+ * @returns Promise containing the vNext workflow execution results
1009
+ */
1010
+ async stream(params) {
1011
+ const searchParams = new URLSearchParams();
1012
+ if (!!params?.runId) {
1013
+ searchParams.set("runId", params.runId);
1014
+ }
1015
+ const runtimeContext = params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : void 0;
1016
+ const response = await this.request(
1017
+ `/api/workflows/${this.workflowId}/stream?${searchParams.toString()}`,
1018
+ {
1019
+ method: "POST",
1020
+ body: { inputData: params.inputData, runtimeContext },
1021
+ stream: true
1022
+ }
1023
+ );
1024
+ if (!response.ok) {
1025
+ throw new Error(`Failed to stream vNext workflow: ${response.statusText}`);
1026
+ }
1027
+ if (!response.body) {
1028
+ throw new Error("Response body is null");
1029
+ }
1030
+ const transformStream = new TransformStream({
1031
+ start() {
1032
+ },
1033
+ async transform(chunk, controller) {
1034
+ try {
1035
+ const decoded = new TextDecoder().decode(chunk);
1036
+ const chunks = decoded.split(RECORD_SEPARATOR2);
1037
+ for (const chunk2 of chunks) {
1038
+ if (chunk2) {
1039
+ try {
1040
+ const parsedChunk = JSON.parse(chunk2);
1041
+ controller.enqueue(parsedChunk);
1042
+ } catch {
1043
+ }
1044
+ }
1045
+ }
1046
+ } catch {
1047
+ }
1048
+ }
1049
+ });
1050
+ return response.body.pipeThrough(transformStream);
1051
+ }
1052
+ /**
1053
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
1054
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
1055
+ * @returns Promise containing the workflow resume results
1056
+ */
1057
+ resumeAsync(params) {
1058
+ const runtimeContext = parseClientRuntimeContext(params.runtimeContext);
1059
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
1060
+ method: "POST",
1061
+ body: {
1062
+ step: params.step,
1063
+ resumeData: params.resumeData,
1064
+ runtimeContext
1065
+ }
1066
+ });
1067
+ }
1068
+ /**
1069
+ * Watches workflow transitions in real-time
1070
+ * @param runId - Optional run ID to filter the watch stream
1071
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
1072
+ */
1073
+ async watch({ runId }, onRecord) {
1074
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
1075
+ stream: true
1076
+ });
1077
+ if (!response.ok) {
1078
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
1079
+ }
1080
+ if (!response.body) {
1081
+ throw new Error("Response body is null");
1082
+ }
1083
+ for await (const record of this.streamProcessor(response.body)) {
1084
+ if (typeof record === "string") {
1085
+ onRecord(JSON.parse(record));
1086
+ } else {
1087
+ onRecord(record);
1088
+ }
1089
+ }
1090
+ }
1091
+ /**
1092
+ * Creates a new ReadableStream from an iterable or async iterable of objects,
1093
+ * serializing each as JSON and separating them with the record separator (\x1E).
1094
+ *
1095
+ * @param records - An iterable or async iterable of objects to stream
1096
+ * @returns A ReadableStream emitting the records as JSON strings separated by the record separator
1097
+ */
1098
+ static createRecordStream(records) {
1099
+ const encoder = new TextEncoder();
1100
+ return new ReadableStream({
1101
+ async start(controller) {
1102
+ try {
1103
+ for await (const record of records) {
1104
+ const json = JSON.stringify(record) + RECORD_SEPARATOR2;
1105
+ controller.enqueue(encoder.encode(json));
1106
+ }
1107
+ controller.close();
1108
+ } catch (err) {
1109
+ controller.error(err);
1110
+ }
1111
+ }
1112
+ });
1113
+ }
1114
+ };
1115
+
1116
+ // src/resources/a2a.ts
1117
+ var A2A = class extends BaseResource {
1118
+ constructor(options, agentId) {
1119
+ super(options);
1120
+ this.agentId = agentId;
1121
+ }
1122
+ /**
1123
+ * Get the agent card with metadata about the agent
1124
+ * @returns Promise containing the agent card information
1125
+ */
1126
+ async getCard() {
1127
+ return this.request(`/.well-known/${this.agentId}/agent.json`);
1128
+ }
1129
+ /**
1130
+ * Send a message to the agent and get a response
1131
+ * @param params - Parameters for the task
1132
+ * @returns Promise containing the task response
1133
+ */
1134
+ async sendMessage(params) {
1135
+ const response = await this.request(`/a2a/${this.agentId}`, {
1136
+ method: "POST",
1137
+ body: {
1138
+ method: "tasks/send",
1139
+ params
1140
+ }
1141
+ });
1142
+ return { task: response.result };
1143
+ }
1144
+ /**
1145
+ * Get the status and result of a task
1146
+ * @param params - Parameters for querying the task
1147
+ * @returns Promise containing the task response
1148
+ */
1149
+ async getTask(params) {
1150
+ const response = await this.request(`/a2a/${this.agentId}`, {
1151
+ method: "POST",
1152
+ body: {
1153
+ method: "tasks/get",
1154
+ params
1155
+ }
1156
+ });
1157
+ return response.result;
1158
+ }
1159
+ /**
1160
+ * Cancel a running task
1161
+ * @param params - Parameters identifying the task to cancel
1162
+ * @returns Promise containing the task response
1163
+ */
1164
+ async cancelTask(params) {
1165
+ return this.request(`/a2a/${this.agentId}`, {
1166
+ method: "POST",
1167
+ body: {
1168
+ method: "tasks/cancel",
1169
+ params
1170
+ }
1171
+ });
1172
+ }
1173
+ /**
1174
+ * Send a message and subscribe to streaming updates (not fully implemented)
1175
+ * @param params - Parameters for the task
1176
+ * @returns Promise containing the task response
1177
+ */
1178
+ async sendAndSubscribe(params) {
1179
+ return this.request(`/a2a/${this.agentId}`, {
1180
+ method: "POST",
1181
+ body: {
1182
+ method: "tasks/sendSubscribe",
1183
+ params
1184
+ },
1185
+ stream: true
1186
+ });
1187
+ }
1188
+ };
1189
+
1190
+ // src/resources/mcp-tool.ts
1191
+ var MCPTool = class extends BaseResource {
1192
+ serverId;
1193
+ toolId;
1194
+ constructor(options, serverId, toolId) {
1195
+ super(options);
1196
+ this.serverId = serverId;
1197
+ this.toolId = toolId;
1198
+ }
1199
+ /**
1200
+ * Retrieves details about this specific tool from the MCP server.
1201
+ * @returns Promise containing the tool's information (name, description, schema).
1202
+ */
1203
+ details() {
1204
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}`);
1205
+ }
1206
+ /**
1207
+ * Executes this specific tool on the MCP server.
1208
+ * @param params - Parameters for tool execution, including data/args and optional runtimeContext.
1209
+ * @returns Promise containing the result of the tool execution.
1210
+ */
1211
+ execute(params) {
1212
+ const body = {};
1213
+ if (params.data !== void 0) body.data = params.data;
1214
+ if (params.runtimeContext !== void 0) {
1215
+ body.runtimeContext = params.runtimeContext;
1216
+ }
1217
+ return this.request(`/api/mcp/${this.serverId}/tools/${this.toolId}/execute`, {
1218
+ method: "POST",
1219
+ body: Object.keys(body).length > 0 ? body : void 0
549
1220
  });
550
1221
  }
551
1222
  };
@@ -562,6 +1233,21 @@ var MastraClient = class extends BaseResource {
562
1233
  getAgents() {
563
1234
  return this.request("/api/agents");
564
1235
  }
1236
+ async getAGUI({ resourceId }) {
1237
+ const agents = await this.getAgents();
1238
+ return Object.entries(agents).reduce(
1239
+ (acc, [agentId]) => {
1240
+ const agent = this.getAgent(agentId);
1241
+ acc[agentId] = new AGUIAdapter({
1242
+ agentId,
1243
+ agent,
1244
+ resourceId
1245
+ });
1246
+ return acc;
1247
+ },
1248
+ {}
1249
+ );
1250
+ }
565
1251
  /**
566
1252
  * Gets an agent instance by ID
567
1253
  * @param agentId - ID of the agent to retrieve
@@ -627,6 +1313,21 @@ var MastraClient = class extends BaseResource {
627
1313
  getTool(toolId) {
628
1314
  return new Tool(this.options, toolId);
629
1315
  }
1316
+ /**
1317
+ * Retrieves all available legacy workflows
1318
+ * @returns Promise containing map of legacy workflow IDs to legacy workflow details
1319
+ */
1320
+ getLegacyWorkflows() {
1321
+ return this.request("/api/workflows/legacy");
1322
+ }
1323
+ /**
1324
+ * Gets a legacy workflow instance by ID
1325
+ * @param workflowId - ID of the legacy workflow to retrieve
1326
+ * @returns Legacy Workflow instance
1327
+ */
1328
+ getLegacyWorkflow(workflowId) {
1329
+ return new LegacyWorkflow(this.options, workflowId);
1330
+ }
630
1331
  /**
631
1332
  * Retrieves all available workflows
632
1333
  * @returns Promise containing map of workflow IDs to workflow details
@@ -656,7 +1357,41 @@ var MastraClient = class extends BaseResource {
656
1357
  * @returns Promise containing array of log messages
657
1358
  */
658
1359
  getLogs(params) {
659
- return this.request(`/api/logs?transportId=${params.transportId}`);
1360
+ const { transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
1361
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
1362
+ const searchParams = new URLSearchParams();
1363
+ if (transportId) {
1364
+ searchParams.set("transportId", transportId);
1365
+ }
1366
+ if (fromDate) {
1367
+ searchParams.set("fromDate", fromDate.toISOString());
1368
+ }
1369
+ if (toDate) {
1370
+ searchParams.set("toDate", toDate.toISOString());
1371
+ }
1372
+ if (logLevel) {
1373
+ searchParams.set("logLevel", logLevel);
1374
+ }
1375
+ if (page) {
1376
+ searchParams.set("page", String(page));
1377
+ }
1378
+ if (perPage) {
1379
+ searchParams.set("perPage", String(perPage));
1380
+ }
1381
+ if (_filters) {
1382
+ if (Array.isArray(_filters)) {
1383
+ for (const filter of _filters) {
1384
+ searchParams.append("filters", filter);
1385
+ }
1386
+ } else {
1387
+ searchParams.set("filters", _filters);
1388
+ }
1389
+ }
1390
+ if (searchParams.size) {
1391
+ return this.request(`/api/logs?${searchParams}`);
1392
+ } else {
1393
+ return this.request(`/api/logs`);
1394
+ }
660
1395
  }
661
1396
  /**
662
1397
  * Gets logs for a specific run
@@ -664,7 +1399,44 @@ var MastraClient = class extends BaseResource {
664
1399
  * @returns Promise containing array of log messages
665
1400
  */
666
1401
  getLogForRun(params) {
667
- return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
1402
+ const { runId, transportId, fromDate, toDate, logLevel, filters, page, perPage } = params;
1403
+ const _filters = filters ? Object.entries(filters).map(([key, value]) => `${key}:${value}`) : [];
1404
+ const searchParams = new URLSearchParams();
1405
+ if (runId) {
1406
+ searchParams.set("runId", runId);
1407
+ }
1408
+ if (transportId) {
1409
+ searchParams.set("transportId", transportId);
1410
+ }
1411
+ if (fromDate) {
1412
+ searchParams.set("fromDate", fromDate.toISOString());
1413
+ }
1414
+ if (toDate) {
1415
+ searchParams.set("toDate", toDate.toISOString());
1416
+ }
1417
+ if (logLevel) {
1418
+ searchParams.set("logLevel", logLevel);
1419
+ }
1420
+ if (page) {
1421
+ searchParams.set("page", String(page));
1422
+ }
1423
+ if (perPage) {
1424
+ searchParams.set("perPage", String(perPage));
1425
+ }
1426
+ if (_filters) {
1427
+ if (Array.isArray(_filters)) {
1428
+ for (const filter of _filters) {
1429
+ searchParams.append("filters", filter);
1430
+ }
1431
+ } else {
1432
+ searchParams.set("filters", _filters);
1433
+ }
1434
+ }
1435
+ if (searchParams.size) {
1436
+ return this.request(`/api/logs/${runId}?${searchParams}`);
1437
+ } else {
1438
+ return this.request(`/api/logs/${runId}`);
1439
+ }
668
1440
  }
669
1441
  /**
670
1442
  * List of all log transports
@@ -679,7 +1451,7 @@ var MastraClient = class extends BaseResource {
679
1451
  * @returns Promise containing telemetry data
680
1452
  */
681
1453
  getTelemetry(params) {
682
- const { name, scope, page, perPage, attribute } = params || {};
1454
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
683
1455
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
684
1456
  const searchParams = new URLSearchParams();
685
1457
  if (name) {
@@ -703,6 +1475,12 @@ var MastraClient = class extends BaseResource {
703
1475
  searchParams.set("attribute", _attribute);
704
1476
  }
705
1477
  }
1478
+ if (fromDate) {
1479
+ searchParams.set("fromDate", fromDate.toISOString());
1480
+ }
1481
+ if (toDate) {
1482
+ searchParams.set("toDate", toDate.toISOString());
1483
+ }
706
1484
  if (searchParams.size) {
707
1485
  return this.request(`/api/telemetry?${searchParams}`);
708
1486
  } else {
@@ -724,6 +1502,62 @@ var MastraClient = class extends BaseResource {
724
1502
  getNetwork(networkId) {
725
1503
  return new Network(this.options, networkId);
726
1504
  }
1505
+ /**
1506
+ * Retrieves a list of available MCP servers.
1507
+ * @param params - Optional parameters for pagination (limit, offset).
1508
+ * @returns Promise containing the list of MCP servers and pagination info.
1509
+ */
1510
+ getMcpServers(params) {
1511
+ const searchParams = new URLSearchParams();
1512
+ if (params?.limit !== void 0) {
1513
+ searchParams.set("limit", String(params.limit));
1514
+ }
1515
+ if (params?.offset !== void 0) {
1516
+ searchParams.set("offset", String(params.offset));
1517
+ }
1518
+ const queryString = searchParams.toString();
1519
+ return this.request(`/api/mcp/v0/servers${queryString ? `?${queryString}` : ""}`);
1520
+ }
1521
+ /**
1522
+ * Retrieves detailed information for a specific MCP server.
1523
+ * @param serverId - The ID of the MCP server to retrieve.
1524
+ * @param params - Optional parameters, e.g., specific version.
1525
+ * @returns Promise containing the detailed MCP server information.
1526
+ */
1527
+ getMcpServerDetails(serverId, params) {
1528
+ const searchParams = new URLSearchParams();
1529
+ if (params?.version) {
1530
+ searchParams.set("version", params.version);
1531
+ }
1532
+ const queryString = searchParams.toString();
1533
+ return this.request(`/api/mcp/v0/servers/${serverId}${queryString ? `?${queryString}` : ""}`);
1534
+ }
1535
+ /**
1536
+ * Retrieves a list of tools for a specific MCP server.
1537
+ * @param serverId - The ID of the MCP server.
1538
+ * @returns Promise containing the list of tools.
1539
+ */
1540
+ getMcpServerTools(serverId) {
1541
+ return this.request(`/api/mcp/${serverId}/tools`);
1542
+ }
1543
+ /**
1544
+ * Gets an MCPTool resource instance for a specific tool on an MCP server.
1545
+ * This instance can then be used to fetch details or execute the tool.
1546
+ * @param serverId - The ID of the MCP server.
1547
+ * @param toolId - The ID of the tool.
1548
+ * @returns MCPTool instance.
1549
+ */
1550
+ getMcpServerTool(serverId, toolId) {
1551
+ return new MCPTool(this.options, serverId, toolId);
1552
+ }
1553
+ /**
1554
+ * Gets an A2A client for interacting with an agent via the A2A protocol
1555
+ * @param agentId - ID of the agent to interact with
1556
+ * @returns A2A client instance
1557
+ */
1558
+ getA2A(agentId) {
1559
+ return new A2A(this.options, agentId);
1560
+ }
727
1561
  };
728
1562
 
729
1563
  exports.MastraClient = MastraClient;