@mastra/client-js 0.0.0-storage-20250225005900 → 0.0.0-trigger-playground-ui-package-20250506151043

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 ADDED
@@ -0,0 +1,1144 @@
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
3
+ import { processDataStream } from '@ai-sdk/ui-utils';
4
+ import { ZodSchema } from 'zod';
5
+ import { zodToJsonSchema } from 'zod-to-json-schema';
6
+
7
+ // src/adapters/agui.ts
8
+ var AGUIAdapter = class extends AbstractAgent {
9
+ agent;
10
+ resourceId;
11
+ constructor({ agent, agentId, resourceId, ...rest }) {
12
+ super({
13
+ agentId,
14
+ ...rest
15
+ });
16
+ this.agent = agent;
17
+ this.resourceId = resourceId;
18
+ }
19
+ run(input) {
20
+ return new Observable((subscriber) => {
21
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
22
+ subscriber.next({
23
+ type: EventType.RUN_STARTED,
24
+ threadId: input.threadId,
25
+ runId: input.runId
26
+ });
27
+ this.agent.stream({
28
+ threadId: input.threadId,
29
+ resourceId: this.resourceId ?? "",
30
+ runId: input.runId,
31
+ messages: convertedMessages,
32
+ clientTools: input.tools.reduce(
33
+ (acc, tool) => {
34
+ acc[tool.name] = {
35
+ id: tool.name,
36
+ description: tool.description,
37
+ inputSchema: tool.parameters
38
+ };
39
+ return acc;
40
+ },
41
+ {}
42
+ )
43
+ }).then((response) => {
44
+ let currentMessageId = void 0;
45
+ return response.processDataStream({
46
+ onTextPart: (text) => {
47
+ if (currentMessageId === void 0) {
48
+ currentMessageId = generateUUID();
49
+ const message2 = {
50
+ type: EventType.TEXT_MESSAGE_START,
51
+ messageId: currentMessageId,
52
+ role: "assistant"
53
+ };
54
+ subscriber.next(message2);
55
+ }
56
+ const message = {
57
+ type: EventType.TEXT_MESSAGE_CONTENT,
58
+ messageId: currentMessageId,
59
+ delta: text
60
+ };
61
+ subscriber.next(message);
62
+ },
63
+ onFinishMessagePart: (message) => {
64
+ console.log("onFinishMessagePart", message);
65
+ if (currentMessageId !== void 0) {
66
+ const message2 = {
67
+ type: EventType.TEXT_MESSAGE_END,
68
+ messageId: currentMessageId
69
+ };
70
+ subscriber.next(message2);
71
+ }
72
+ subscriber.next({
73
+ type: EventType.RUN_FINISHED,
74
+ threadId: input.threadId,
75
+ runId: input.runId
76
+ });
77
+ subscriber.complete();
78
+ },
79
+ onToolCallPart(streamPart) {
80
+ const parentMessageId = currentMessageId || generateUUID();
81
+ subscriber.next({
82
+ type: EventType.TOOL_CALL_START,
83
+ toolCallId: streamPart.toolCallId,
84
+ toolCallName: streamPart.toolName,
85
+ parentMessageId
86
+ });
87
+ subscriber.next({
88
+ type: EventType.TOOL_CALL_ARGS,
89
+ toolCallId: streamPart.toolCallId,
90
+ delta: JSON.stringify(streamPart.args),
91
+ parentMessageId
92
+ });
93
+ subscriber.next({
94
+ type: EventType.TOOL_CALL_END,
95
+ toolCallId: streamPart.toolCallId,
96
+ parentMessageId
97
+ });
98
+ }
99
+ });
100
+ }).catch((error) => {
101
+ console.log("error", error);
102
+ subscriber.error(error);
103
+ });
104
+ return () => {
105
+ };
106
+ });
107
+ }
108
+ };
109
+ function generateUUID() {
110
+ if (typeof crypto !== "undefined") {
111
+ if (typeof crypto.randomUUID === "function") {
112
+ return crypto.randomUUID();
113
+ }
114
+ if (typeof crypto.getRandomValues === "function") {
115
+ const buffer = new Uint8Array(16);
116
+ crypto.getRandomValues(buffer);
117
+ buffer[6] = buffer[6] & 15 | 64;
118
+ buffer[8] = buffer[8] & 63 | 128;
119
+ let hex = "";
120
+ for (let i = 0; i < 16; i++) {
121
+ hex += buffer[i].toString(16).padStart(2, "0");
122
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += "-";
123
+ }
124
+ return hex;
125
+ }
126
+ }
127
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
128
+ const r = Math.random() * 16 | 0;
129
+ const v = c === "x" ? r : r & 3 | 8;
130
+ return v.toString(16);
131
+ });
132
+ }
133
+ function convertMessagesToMastraMessages(messages) {
134
+ const result = [];
135
+ for (const message of messages) {
136
+ if (message.role === "assistant") {
137
+ const parts = message.content ? [{ type: "text", text: message.content }] : [];
138
+ for (const toolCall of message.toolCalls ?? []) {
139
+ parts.push({
140
+ type: "tool-call",
141
+ toolCallId: toolCall.id,
142
+ toolName: toolCall.function.name,
143
+ args: JSON.parse(toolCall.function.arguments)
144
+ });
145
+ }
146
+ result.push({
147
+ role: "assistant",
148
+ content: parts
149
+ });
150
+ } else if (message.role === "user") {
151
+ result.push({
152
+ role: "user",
153
+ content: message.content || ""
154
+ });
155
+ } else if (message.role === "tool") {
156
+ result.push({
157
+ role: "tool",
158
+ content: [
159
+ {
160
+ type: "tool-result",
161
+ toolCallId: message.toolCallId,
162
+ toolName: "unknown",
163
+ result: message.content
164
+ }
165
+ ]
166
+ });
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+
172
+ // src/resources/base.ts
173
+ var BaseResource = class {
174
+ options;
175
+ constructor(options) {
176
+ this.options = options;
177
+ }
178
+ /**
179
+ * Makes an HTTP request to the API with retries and exponential backoff
180
+ * @param path - The API endpoint path
181
+ * @param options - Optional request configuration
182
+ * @returns Promise containing the response data
183
+ */
184
+ async request(path, options = {}) {
185
+ let lastError = null;
186
+ const { baseUrl, retries = 3, backoffMs = 100, maxBackoffMs = 1e3, headers = {} } = this.options;
187
+ let delay = backoffMs;
188
+ for (let attempt = 0; attempt <= retries; attempt++) {
189
+ try {
190
+ const response = await fetch(`${baseUrl}${path}`, {
191
+ ...options,
192
+ headers: {
193
+ ...headers,
194
+ ...options.headers
195
+ // TODO: Bring this back once we figure out what we/users need to do to make this work with cross-origin requests
196
+ // 'x-mastra-client-type': 'js',
197
+ },
198
+ body: options.body instanceof FormData ? options.body : options.body ? JSON.stringify(options.body) : void 0
199
+ });
200
+ if (!response.ok) {
201
+ const errorBody = await response.text();
202
+ let errorMessage = `HTTP error! status: ${response.status}`;
203
+ try {
204
+ const errorJson = JSON.parse(errorBody);
205
+ errorMessage += ` - ${JSON.stringify(errorJson)}`;
206
+ } catch {
207
+ if (errorBody) {
208
+ errorMessage += ` - ${errorBody}`;
209
+ }
210
+ }
211
+ throw new Error(errorMessage);
212
+ }
213
+ if (options.stream) {
214
+ return response;
215
+ }
216
+ const data = await response.json();
217
+ return data;
218
+ } catch (error) {
219
+ lastError = error;
220
+ if (attempt === retries) {
221
+ break;
222
+ }
223
+ await new Promise((resolve) => setTimeout(resolve, delay));
224
+ delay = Math.min(delay * 2, maxBackoffMs);
225
+ }
226
+ }
227
+ throw lastError || new Error("Request failed");
228
+ }
229
+ };
230
+
231
+ // src/resources/agent.ts
232
+ var AgentVoice = class extends BaseResource {
233
+ constructor(options, agentId) {
234
+ super(options);
235
+ this.agentId = agentId;
236
+ this.agentId = agentId;
237
+ }
238
+ /**
239
+ * Convert text to speech using the agent's voice provider
240
+ * @param text - Text to convert to speech
241
+ * @param options - Optional provider-specific options for speech generation
242
+ * @returns Promise containing the audio data
243
+ */
244
+ async speak(text, options) {
245
+ return this.request(`/api/agents/${this.agentId}/voice/speak`, {
246
+ method: "POST",
247
+ headers: {
248
+ "Content-Type": "application/json"
249
+ },
250
+ body: { input: text, options },
251
+ stream: true
252
+ });
253
+ }
254
+ /**
255
+ * Convert speech to text using the agent's voice provider
256
+ * @param audio - Audio data to transcribe
257
+ * @param options - Optional provider-specific options
258
+ * @returns Promise containing the transcribed text
259
+ */
260
+ listen(audio, options) {
261
+ const formData = new FormData();
262
+ formData.append("audio", audio);
263
+ if (options) {
264
+ formData.append("options", JSON.stringify(options));
265
+ }
266
+ return this.request(`/api/agents/${this.agentId}/voice/listen`, {
267
+ method: "POST",
268
+ body: formData
269
+ });
270
+ }
271
+ /**
272
+ * Get available speakers for the agent's voice provider
273
+ * @returns Promise containing list of available speakers
274
+ */
275
+ getSpeakers() {
276
+ return this.request(`/api/agents/${this.agentId}/voice/speakers`);
277
+ }
278
+ };
279
+ var Agent = class extends BaseResource {
280
+ constructor(options, agentId) {
281
+ super(options);
282
+ this.agentId = agentId;
283
+ this.voice = new AgentVoice(options, this.agentId);
284
+ }
285
+ voice;
286
+ /**
287
+ * Retrieves details about the agent
288
+ * @returns Promise containing agent details including model and instructions
289
+ */
290
+ details() {
291
+ return this.request(`/api/agents/${this.agentId}`);
292
+ }
293
+ /**
294
+ * Generates a response from the agent
295
+ * @param params - Generation parameters including prompt
296
+ * @returns Promise containing the generated response
297
+ */
298
+ generate(params) {
299
+ const processedParams = {
300
+ ...params,
301
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
302
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
303
+ };
304
+ return this.request(`/api/agents/${this.agentId}/generate`, {
305
+ method: "POST",
306
+ body: processedParams
307
+ });
308
+ }
309
+ /**
310
+ * Streams a response from the agent
311
+ * @param params - Stream parameters including prompt
312
+ * @returns Promise containing the enhanced Response object with processDataStream method
313
+ */
314
+ async stream(params) {
315
+ const processedParams = {
316
+ ...params,
317
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
318
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
319
+ };
320
+ const response = await this.request(`/api/agents/${this.agentId}/stream`, {
321
+ method: "POST",
322
+ body: processedParams,
323
+ stream: true
324
+ });
325
+ if (!response.body) {
326
+ throw new Error("No response body");
327
+ }
328
+ response.processDataStream = async (options = {}) => {
329
+ await processDataStream({
330
+ stream: response.body,
331
+ ...options
332
+ });
333
+ };
334
+ return response;
335
+ }
336
+ /**
337
+ * Gets details about a specific tool available to the agent
338
+ * @param toolId - ID of the tool to retrieve
339
+ * @returns Promise containing tool details
340
+ */
341
+ getTool(toolId) {
342
+ return this.request(`/api/agents/${this.agentId}/tools/${toolId}`);
343
+ }
344
+ /**
345
+ * Retrieves evaluation results for the agent
346
+ * @returns Promise containing agent evaluations
347
+ */
348
+ evals() {
349
+ return this.request(`/api/agents/${this.agentId}/evals/ci`);
350
+ }
351
+ /**
352
+ * Retrieves live evaluation results for the agent
353
+ * @returns Promise containing live agent evaluations
354
+ */
355
+ liveEvals() {
356
+ return this.request(`/api/agents/${this.agentId}/evals/live`);
357
+ }
358
+ };
359
+ var Network = class extends BaseResource {
360
+ constructor(options, networkId) {
361
+ super(options);
362
+ this.networkId = networkId;
363
+ }
364
+ /**
365
+ * Retrieves details about the network
366
+ * @returns Promise containing network details
367
+ */
368
+ details() {
369
+ return this.request(`/api/networks/${this.networkId}`);
370
+ }
371
+ /**
372
+ * Generates a response from the agent
373
+ * @param params - Generation parameters including prompt
374
+ * @returns Promise containing the generated response
375
+ */
376
+ generate(params) {
377
+ const processedParams = {
378
+ ...params,
379
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
380
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
381
+ };
382
+ return this.request(`/api/networks/${this.networkId}/generate`, {
383
+ method: "POST",
384
+ body: processedParams
385
+ });
386
+ }
387
+ /**
388
+ * Streams a response from the agent
389
+ * @param params - Stream parameters including prompt
390
+ * @returns Promise containing the enhanced Response object with processDataStream method
391
+ */
392
+ async stream(params) {
393
+ const processedParams = {
394
+ ...params,
395
+ output: params.output instanceof ZodSchema ? zodToJsonSchema(params.output) : params.output,
396
+ experimental_output: params.experimental_output instanceof ZodSchema ? zodToJsonSchema(params.experimental_output) : params.experimental_output
397
+ };
398
+ const response = await this.request(`/api/networks/${this.networkId}/stream`, {
399
+ method: "POST",
400
+ body: processedParams,
401
+ stream: true
402
+ });
403
+ if (!response.body) {
404
+ throw new Error("No response body");
405
+ }
406
+ response.processDataStream = async (options = {}) => {
407
+ await processDataStream({
408
+ stream: response.body,
409
+ ...options
410
+ });
411
+ };
412
+ return response;
413
+ }
414
+ };
415
+
416
+ // src/resources/memory-thread.ts
417
+ var MemoryThread = class extends BaseResource {
418
+ constructor(options, threadId, agentId) {
419
+ super(options);
420
+ this.threadId = threadId;
421
+ this.agentId = agentId;
422
+ }
423
+ /**
424
+ * Retrieves the memory thread details
425
+ * @returns Promise containing thread details including title and metadata
426
+ */
427
+ get() {
428
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`);
429
+ }
430
+ /**
431
+ * Updates the memory thread properties
432
+ * @param params - Update parameters including title and metadata
433
+ * @returns Promise containing updated thread details
434
+ */
435
+ update(params) {
436
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
437
+ method: "PATCH",
438
+ body: params
439
+ });
440
+ }
441
+ /**
442
+ * Deletes the memory thread
443
+ * @returns Promise containing deletion result
444
+ */
445
+ delete() {
446
+ return this.request(`/api/memory/threads/${this.threadId}?agentId=${this.agentId}`, {
447
+ method: "DELETE"
448
+ });
449
+ }
450
+ /**
451
+ * Retrieves messages associated with the thread
452
+ * @returns Promise containing thread messages and UI messages
453
+ */
454
+ getMessages() {
455
+ return this.request(`/api/memory/threads/${this.threadId}/messages?agentId=${this.agentId}`);
456
+ }
457
+ };
458
+
459
+ // src/resources/vector.ts
460
+ var Vector = class extends BaseResource {
461
+ constructor(options, vectorName) {
462
+ super(options);
463
+ this.vectorName = vectorName;
464
+ }
465
+ /**
466
+ * Retrieves details about a specific vector index
467
+ * @param indexName - Name of the index to get details for
468
+ * @returns Promise containing vector index details
469
+ */
470
+ details(indexName) {
471
+ return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`);
472
+ }
473
+ /**
474
+ * Deletes a vector index
475
+ * @param indexName - Name of the index to delete
476
+ * @returns Promise indicating deletion success
477
+ */
478
+ delete(indexName) {
479
+ return this.request(`/api/vector/${this.vectorName}/indexes/${indexName}`, {
480
+ method: "DELETE"
481
+ });
482
+ }
483
+ /**
484
+ * Retrieves a list of all available indexes
485
+ * @returns Promise containing array of index names
486
+ */
487
+ getIndexes() {
488
+ return this.request(`/api/vector/${this.vectorName}/indexes`);
489
+ }
490
+ /**
491
+ * Creates a new vector index
492
+ * @param params - Parameters for index creation including dimension and metric
493
+ * @returns Promise indicating creation success
494
+ */
495
+ createIndex(params) {
496
+ return this.request(`/api/vector/${this.vectorName}/create-index`, {
497
+ method: "POST",
498
+ body: params
499
+ });
500
+ }
501
+ /**
502
+ * Upserts vectors into an index
503
+ * @param params - Parameters containing vectors, metadata, and optional IDs
504
+ * @returns Promise containing array of vector IDs
505
+ */
506
+ upsert(params) {
507
+ return this.request(`/api/vector/${this.vectorName}/upsert`, {
508
+ method: "POST",
509
+ body: params
510
+ });
511
+ }
512
+ /**
513
+ * Queries vectors in an index
514
+ * @param params - Query parameters including query vector and search options
515
+ * @returns Promise containing query results
516
+ */
517
+ query(params) {
518
+ return this.request(`/api/vector/${this.vectorName}/query`, {
519
+ method: "POST",
520
+ body: params
521
+ });
522
+ }
523
+ };
524
+
525
+ // src/resources/workflow.ts
526
+ var RECORD_SEPARATOR = "";
527
+ var Workflow = class extends BaseResource {
528
+ constructor(options, workflowId) {
529
+ super(options);
530
+ this.workflowId = workflowId;
531
+ }
532
+ /**
533
+ * Retrieves details about the workflow
534
+ * @returns Promise containing workflow details including steps and graphs
535
+ */
536
+ details() {
537
+ return this.request(`/api/workflows/${this.workflowId}`);
538
+ }
539
+ /**
540
+ * Retrieves all runs for a workflow
541
+ * @param params - Parameters for filtering runs
542
+ * @returns Promise containing workflow runs array
543
+ */
544
+ runs(params) {
545
+ const searchParams = new URLSearchParams();
546
+ if (params?.fromDate) {
547
+ searchParams.set("fromDate", params.fromDate.toISOString());
548
+ }
549
+ if (params?.toDate) {
550
+ searchParams.set("toDate", params.toDate.toISOString());
551
+ }
552
+ if (params?.limit) {
553
+ searchParams.set("limit", String(params.limit));
554
+ }
555
+ if (params?.offset) {
556
+ searchParams.set("offset", String(params.offset));
557
+ }
558
+ if (params?.resourceId) {
559
+ searchParams.set("resourceId", params.resourceId);
560
+ }
561
+ if (searchParams.size) {
562
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
563
+ } else {
564
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
565
+ }
566
+ }
567
+ /**
568
+ * @deprecated Use `startAsync` instead
569
+ * Executes the workflow with the provided parameters
570
+ * @param params - Parameters required for workflow execution
571
+ * @returns Promise containing the workflow execution results
572
+ */
573
+ execute(params) {
574
+ return this.request(`/api/workflows/${this.workflowId}/execute`, {
575
+ method: "POST",
576
+ body: params
577
+ });
578
+ }
579
+ /**
580
+ * Creates a new workflow run
581
+ * @returns Promise containing the generated run ID
582
+ */
583
+ createRun(params) {
584
+ const searchParams = new URLSearchParams();
585
+ if (!!params?.runId) {
586
+ searchParams.set("runId", params.runId);
587
+ }
588
+ return this.request(`/api/workflows/${this.workflowId}/createRun?${searchParams.toString()}`, {
589
+ method: "POST"
590
+ });
591
+ }
592
+ /**
593
+ * Starts a workflow run synchronously without waiting for the workflow to complete
594
+ * @param params - Object containing the runId and triggerData
595
+ * @returns Promise containing success message
596
+ */
597
+ start(params) {
598
+ return this.request(`/api/workflows/${this.workflowId}/start?runId=${params.runId}`, {
599
+ method: "POST",
600
+ body: params?.triggerData
601
+ });
602
+ }
603
+ /**
604
+ * Resumes a suspended workflow step synchronously without waiting for the workflow to complete
605
+ * @param stepId - ID of the step to resume
606
+ * @param runId - ID of the workflow run
607
+ * @param context - Context to resume the workflow with
608
+ * @returns Promise containing the workflow resume results
609
+ */
610
+ resume({
611
+ stepId,
612
+ runId,
613
+ context
614
+ }) {
615
+ return this.request(`/api/workflows/${this.workflowId}/resume?runId=${runId}`, {
616
+ method: "POST",
617
+ body: {
618
+ stepId,
619
+ context
620
+ }
621
+ });
622
+ }
623
+ /**
624
+ * Starts a workflow run asynchronously and returns a promise that resolves when the workflow is complete
625
+ * @param params - Object containing the optional runId and triggerData
626
+ * @returns Promise containing the workflow execution results
627
+ */
628
+ startAsync(params) {
629
+ const searchParams = new URLSearchParams();
630
+ if (!!params?.runId) {
631
+ searchParams.set("runId", params.runId);
632
+ }
633
+ return this.request(`/api/workflows/${this.workflowId}/start-async?${searchParams.toString()}`, {
634
+ method: "POST",
635
+ body: params?.triggerData
636
+ });
637
+ }
638
+ /**
639
+ * Resumes a suspended workflow step asynchronously and returns a promise that resolves when the workflow is complete
640
+ * @param params - Object containing the runId, stepId, and context
641
+ * @returns Promise containing the workflow resume results
642
+ */
643
+ resumeAsync(params) {
644
+ return this.request(`/api/workflows/${this.workflowId}/resume-async?runId=${params.runId}`, {
645
+ method: "POST",
646
+ body: {
647
+ stepId: params.stepId,
648
+ context: params.context
649
+ }
650
+ });
651
+ }
652
+ /**
653
+ * Creates an async generator that processes a readable stream and yields records
654
+ * separated by the Record Separator character (\x1E)
655
+ *
656
+ * @param stream - The readable stream to process
657
+ * @returns An async generator that yields parsed records
658
+ */
659
+ async *streamProcessor(stream) {
660
+ const reader = stream.getReader();
661
+ let doneReading = false;
662
+ let buffer = "";
663
+ try {
664
+ while (!doneReading) {
665
+ const { done, value } = await reader.read();
666
+ doneReading = done;
667
+ if (done && !value) continue;
668
+ try {
669
+ const decoded = value ? new TextDecoder().decode(value) : "";
670
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
671
+ buffer = chunks.pop() || "";
672
+ for (const chunk of chunks) {
673
+ if (chunk) {
674
+ if (typeof chunk === "string") {
675
+ try {
676
+ const parsedChunk = JSON.parse(chunk);
677
+ yield parsedChunk;
678
+ } catch {
679
+ }
680
+ }
681
+ }
682
+ }
683
+ } catch {
684
+ }
685
+ }
686
+ if (buffer) {
687
+ try {
688
+ yield JSON.parse(buffer);
689
+ } catch {
690
+ }
691
+ }
692
+ } finally {
693
+ reader.cancel().catch(() => {
694
+ });
695
+ }
696
+ }
697
+ /**
698
+ * Watches workflow transitions in real-time
699
+ * @param runId - Optional run ID to filter the watch stream
700
+ * @returns AsyncGenerator that yields parsed records from the workflow watch stream
701
+ */
702
+ async watch({ runId }, onRecord) {
703
+ const response = await this.request(`/api/workflows/${this.workflowId}/watch?runId=${runId}`, {
704
+ stream: true
705
+ });
706
+ if (!response.ok) {
707
+ throw new Error(`Failed to watch workflow: ${response.statusText}`);
708
+ }
709
+ if (!response.body) {
710
+ throw new Error("Response body is null");
711
+ }
712
+ for await (const record of this.streamProcessor(response.body)) {
713
+ onRecord(record);
714
+ }
715
+ }
716
+ };
717
+
718
+ // src/resources/tool.ts
719
+ var Tool = class extends BaseResource {
720
+ constructor(options, toolId) {
721
+ super(options);
722
+ this.toolId = toolId;
723
+ }
724
+ /**
725
+ * Retrieves details about the tool
726
+ * @returns Promise containing tool details including description and schemas
727
+ */
728
+ details() {
729
+ return this.request(`/api/tools/${this.toolId}`);
730
+ }
731
+ /**
732
+ * Executes the tool with the provided parameters
733
+ * @param params - Parameters required for tool execution
734
+ * @returns Promise containing the tool execution results
735
+ */
736
+ execute(params) {
737
+ const url = new URLSearchParams();
738
+ if (params.runId) {
739
+ url.set("runId", params.runId);
740
+ }
741
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
742
+ method: "POST",
743
+ body: params.data
744
+ });
745
+ }
746
+ };
747
+
748
+ // src/resources/vnext-workflow.ts
749
+ var RECORD_SEPARATOR2 = "";
750
+ var VNextWorkflow = class extends BaseResource {
751
+ constructor(options, workflowId) {
752
+ super(options);
753
+ this.workflowId = workflowId;
754
+ }
755
+ /**
756
+ * Creates an async generator that processes a readable stream and yields vNext workflow records
757
+ * separated by the Record Separator character (\x1E)
758
+ *
759
+ * @param stream - The readable stream to process
760
+ * @returns An async generator that yields parsed records
761
+ */
762
+ async *streamProcessor(stream) {
763
+ const reader = stream.getReader();
764
+ let doneReading = false;
765
+ let buffer = "";
766
+ try {
767
+ while (!doneReading) {
768
+ const { done, value } = await reader.read();
769
+ doneReading = done;
770
+ if (done && !value) continue;
771
+ try {
772
+ const decoded = value ? new TextDecoder().decode(value) : "";
773
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
774
+ buffer = chunks.pop() || "";
775
+ for (const chunk of chunks) {
776
+ if (chunk) {
777
+ if (typeof chunk === "string") {
778
+ try {
779
+ const parsedChunk = JSON.parse(chunk);
780
+ yield parsedChunk;
781
+ } catch {
782
+ }
783
+ }
784
+ }
785
+ }
786
+ } catch {
787
+ }
788
+ }
789
+ if (buffer) {
790
+ try {
791
+ yield JSON.parse(buffer);
792
+ } catch {
793
+ }
794
+ }
795
+ } finally {
796
+ reader.cancel().catch(() => {
797
+ });
798
+ }
799
+ }
800
+ /**
801
+ * Retrieves details about the vNext workflow
802
+ * @returns Promise containing vNext workflow details including steps and graphs
803
+ */
804
+ details() {
805
+ return this.request(`/api/workflows/v-next/${this.workflowId}`);
806
+ }
807
+ /**
808
+ * Retrieves all runs for a vNext workflow
809
+ * @param params - Parameters for filtering runs
810
+ * @returns Promise containing vNext workflow runs array
811
+ */
812
+ runs(params) {
813
+ const searchParams = new URLSearchParams();
814
+ if (params?.fromDate) {
815
+ searchParams.set("fromDate", params.fromDate.toISOString());
816
+ }
817
+ if (params?.toDate) {
818
+ searchParams.set("toDate", params.toDate.toISOString());
819
+ }
820
+ if (params?.limit) {
821
+ searchParams.set("limit", String(params.limit));
822
+ }
823
+ if (params?.offset) {
824
+ searchParams.set("offset", String(params.offset));
825
+ }
826
+ if (params?.resourceId) {
827
+ searchParams.set("resourceId", params.resourceId);
828
+ }
829
+ if (searchParams.size) {
830
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
831
+ } else {
832
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
833
+ }
834
+ }
835
+ /**
836
+ * Creates a new vNext workflow run
837
+ * @param params - Optional object containing the optional runId
838
+ * @returns Promise containing the runId of the created run
839
+ */
840
+ createRun(params) {
841
+ const searchParams = new URLSearchParams();
842
+ if (!!params?.runId) {
843
+ searchParams.set("runId", params.runId);
844
+ }
845
+ return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
846
+ method: "POST"
847
+ });
848
+ }
849
+ /**
850
+ * Starts a vNext workflow run synchronously without waiting for the workflow to complete
851
+ * @param params - Object containing the runId, inputData and runtimeContext
852
+ * @returns Promise containing success message
853
+ */
854
+ start(params) {
855
+ return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
856
+ method: "POST",
857
+ body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
858
+ });
859
+ }
860
+ /**
861
+ * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
862
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
863
+ * @returns Promise containing success message
864
+ */
865
+ resume({
866
+ step,
867
+ runId,
868
+ resumeData,
869
+ runtimeContext
870
+ }) {
871
+ return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
872
+ method: "POST",
873
+ stream: true,
874
+ body: {
875
+ step,
876
+ resumeData,
877
+ runtimeContext
878
+ }
879
+ });
880
+ }
881
+ /**
882
+ * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
883
+ * @param params - Object containing the optional runId, inputData and runtimeContext
884
+ * @returns Promise containing the vNext workflow execution results
885
+ */
886
+ startAsync(params) {
887
+ const searchParams = new URLSearchParams();
888
+ if (!!params?.runId) {
889
+ searchParams.set("runId", params.runId);
890
+ }
891
+ return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
892
+ method: "POST",
893
+ body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
894
+ });
895
+ }
896
+ /**
897
+ * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
898
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
899
+ * @returns Promise containing the vNext workflow resume results
900
+ */
901
+ resumeAsync(params) {
902
+ return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
903
+ method: "POST",
904
+ body: {
905
+ step: params.step,
906
+ resumeData: params.resumeData,
907
+ runtimeContext: params.runtimeContext
908
+ }
909
+ });
910
+ }
911
+ /**
912
+ * Watches vNext workflow transitions in real-time
913
+ * @param runId - Optional run ID to filter the watch stream
914
+ * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
915
+ */
916
+ async watch({ runId }, onRecord) {
917
+ const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
918
+ stream: true
919
+ });
920
+ if (!response.ok) {
921
+ throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
922
+ }
923
+ if (!response.body) {
924
+ throw new Error("Response body is null");
925
+ }
926
+ for await (const record of this.streamProcessor(response.body)) {
927
+ onRecord(record);
928
+ }
929
+ }
930
+ };
931
+
932
+ // src/client.ts
933
+ var MastraClient = class extends BaseResource {
934
+ constructor(options) {
935
+ super(options);
936
+ }
937
+ /**
938
+ * Retrieves all available agents
939
+ * @returns Promise containing map of agent IDs to agent details
940
+ */
941
+ getAgents() {
942
+ return this.request("/api/agents");
943
+ }
944
+ async getAGUI({ resourceId }) {
945
+ const agents = await this.getAgents();
946
+ return Object.entries(agents).reduce(
947
+ (acc, [agentId]) => {
948
+ const agent = this.getAgent(agentId);
949
+ acc[agentId] = new AGUIAdapter({
950
+ agentId,
951
+ agent,
952
+ resourceId
953
+ });
954
+ return acc;
955
+ },
956
+ {}
957
+ );
958
+ }
959
+ /**
960
+ * Gets an agent instance by ID
961
+ * @param agentId - ID of the agent to retrieve
962
+ * @returns Agent instance
963
+ */
964
+ getAgent(agentId) {
965
+ return new Agent(this.options, agentId);
966
+ }
967
+ /**
968
+ * Retrieves memory threads for a resource
969
+ * @param params - Parameters containing the resource ID
970
+ * @returns Promise containing array of memory threads
971
+ */
972
+ getMemoryThreads(params) {
973
+ return this.request(`/api/memory/threads?resourceid=${params.resourceId}&agentId=${params.agentId}`);
974
+ }
975
+ /**
976
+ * Creates a new memory thread
977
+ * @param params - Parameters for creating the memory thread
978
+ * @returns Promise containing the created memory thread
979
+ */
980
+ createMemoryThread(params) {
981
+ return this.request(`/api/memory/threads?agentId=${params.agentId}`, { method: "POST", body: params });
982
+ }
983
+ /**
984
+ * Gets a memory thread instance by ID
985
+ * @param threadId - ID of the memory thread to retrieve
986
+ * @returns MemoryThread instance
987
+ */
988
+ getMemoryThread(threadId, agentId) {
989
+ return new MemoryThread(this.options, threadId, agentId);
990
+ }
991
+ /**
992
+ * Saves messages to memory
993
+ * @param params - Parameters containing messages to save
994
+ * @returns Promise containing the saved messages
995
+ */
996
+ saveMessageToMemory(params) {
997
+ return this.request(`/api/memory/save-messages?agentId=${params.agentId}`, {
998
+ method: "POST",
999
+ body: params
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Gets the status of the memory system
1004
+ * @returns Promise containing memory system status
1005
+ */
1006
+ getMemoryStatus(agentId) {
1007
+ return this.request(`/api/memory/status?agentId=${agentId}`);
1008
+ }
1009
+ /**
1010
+ * Retrieves all available tools
1011
+ * @returns Promise containing map of tool IDs to tool details
1012
+ */
1013
+ getTools() {
1014
+ return this.request("/api/tools");
1015
+ }
1016
+ /**
1017
+ * Gets a tool instance by ID
1018
+ * @param toolId - ID of the tool to retrieve
1019
+ * @returns Tool instance
1020
+ */
1021
+ getTool(toolId) {
1022
+ return new Tool(this.options, toolId);
1023
+ }
1024
+ /**
1025
+ * Retrieves all available workflows
1026
+ * @returns Promise containing map of workflow IDs to workflow details
1027
+ */
1028
+ getWorkflows() {
1029
+ return this.request("/api/workflows");
1030
+ }
1031
+ /**
1032
+ * Gets a workflow instance by ID
1033
+ * @param workflowId - ID of the workflow to retrieve
1034
+ * @returns Workflow instance
1035
+ */
1036
+ getWorkflow(workflowId) {
1037
+ return new Workflow(this.options, workflowId);
1038
+ }
1039
+ /**
1040
+ * Retrieves all available vNext workflows
1041
+ * @returns Promise containing map of vNext workflow IDs to vNext workflow details
1042
+ */
1043
+ getVNextWorkflows() {
1044
+ return this.request("/api/workflows/v-next");
1045
+ }
1046
+ /**
1047
+ * Gets a vNext workflow instance by ID
1048
+ * @param workflowId - ID of the vNext workflow to retrieve
1049
+ * @returns vNext Workflow instance
1050
+ */
1051
+ getVNextWorkflow(workflowId) {
1052
+ return new VNextWorkflow(this.options, workflowId);
1053
+ }
1054
+ /**
1055
+ * Gets a vector instance by name
1056
+ * @param vectorName - Name of the vector to retrieve
1057
+ * @returns Vector instance
1058
+ */
1059
+ getVector(vectorName) {
1060
+ return new Vector(this.options, vectorName);
1061
+ }
1062
+ /**
1063
+ * Retrieves logs
1064
+ * @param params - Parameters for filtering logs
1065
+ * @returns Promise containing array of log messages
1066
+ */
1067
+ getLogs(params) {
1068
+ return this.request(`/api/logs?transportId=${params.transportId}`);
1069
+ }
1070
+ /**
1071
+ * Gets logs for a specific run
1072
+ * @param params - Parameters containing run ID to retrieve
1073
+ * @returns Promise containing array of log messages
1074
+ */
1075
+ getLogForRun(params) {
1076
+ return this.request(`/api/logs/${params.runId}?transportId=${params.transportId}`);
1077
+ }
1078
+ /**
1079
+ * List of all log transports
1080
+ * @returns Promise containing list of log transports
1081
+ */
1082
+ getLogTransports() {
1083
+ return this.request("/api/logs/transports");
1084
+ }
1085
+ /**
1086
+ * List of all traces (paged)
1087
+ * @param params - Parameters for filtering traces
1088
+ * @returns Promise containing telemetry data
1089
+ */
1090
+ getTelemetry(params) {
1091
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
1092
+ const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
1093
+ const searchParams = new URLSearchParams();
1094
+ if (name) {
1095
+ searchParams.set("name", name);
1096
+ }
1097
+ if (scope) {
1098
+ searchParams.set("scope", scope);
1099
+ }
1100
+ if (page) {
1101
+ searchParams.set("page", String(page));
1102
+ }
1103
+ if (perPage) {
1104
+ searchParams.set("perPage", String(perPage));
1105
+ }
1106
+ if (_attribute) {
1107
+ if (Array.isArray(_attribute)) {
1108
+ for (const attr of _attribute) {
1109
+ searchParams.append("attribute", attr);
1110
+ }
1111
+ } else {
1112
+ searchParams.set("attribute", _attribute);
1113
+ }
1114
+ }
1115
+ if (fromDate) {
1116
+ searchParams.set("fromDate", fromDate.toISOString());
1117
+ }
1118
+ if (toDate) {
1119
+ searchParams.set("toDate", toDate.toISOString());
1120
+ }
1121
+ if (searchParams.size) {
1122
+ return this.request(`/api/telemetry?${searchParams}`);
1123
+ } else {
1124
+ return this.request(`/api/telemetry`);
1125
+ }
1126
+ }
1127
+ /**
1128
+ * Retrieves all available networks
1129
+ * @returns Promise containing map of network IDs to network details
1130
+ */
1131
+ getNetworks() {
1132
+ return this.request("/api/networks");
1133
+ }
1134
+ /**
1135
+ * Gets a network instance by ID
1136
+ * @param networkId - ID of the network to retrieve
1137
+ * @returns Network instance
1138
+ */
1139
+ getNetwork(networkId) {
1140
+ return new Network(this.options, networkId);
1141
+ }
1142
+ };
1143
+
1144
+ export { MastraClient };