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