@mastra/client-js 0.0.0-afterToolExecute-20250414225911 → 0.0.0-agui-20250501182100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,173 @@
1
+ import { AbstractAgent, EventType } from '@ag-ui/client';
2
+ import { Observable } from 'rxjs';
1
3
  import { processDataStream } from '@ai-sdk/ui-utils';
2
4
  import { ZodSchema } from 'zod';
3
5
  import { zodToJsonSchema } from 'zod-to-json-schema';
4
6
 
5
- // src/resources/agent.ts
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
+ }
6
171
 
7
172
  // src/resources/base.ts
8
173
  var BaseResource = class {
@@ -371,6 +536,13 @@ var Workflow = class extends BaseResource {
371
536
  details() {
372
537
  return this.request(`/api/workflows/${this.workflowId}`);
373
538
  }
539
+ /**
540
+ * Retrieves all runs for a workflow
541
+ * @returns Promise containing workflow runs array
542
+ */
543
+ runs() {
544
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
545
+ }
374
546
  /**
375
547
  * @deprecated Use `startAsync` instead
376
548
  * Executes the workflow with the provided parameters
@@ -487,7 +659,7 @@ var Workflow = class extends BaseResource {
487
659
  }
488
660
  }
489
661
  }
490
- } catch (error) {
662
+ } catch {
491
663
  }
492
664
  }
493
665
  if (buffer) {
@@ -541,13 +713,180 @@ var Tool = class extends BaseResource {
541
713
  * @returns Promise containing the tool execution results
542
714
  */
543
715
  execute(params) {
544
- return this.request(`/api/tools/${this.toolId}/execute`, {
716
+ const url = new URLSearchParams();
717
+ if (params.runId) {
718
+ url.set("runId", params.runId);
719
+ }
720
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
545
721
  method: "POST",
546
- body: params
722
+ body: params.data
547
723
  });
548
724
  }
549
725
  };
550
726
 
727
+ // src/resources/vnext-workflow.ts
728
+ var RECORD_SEPARATOR2 = "";
729
+ var VNextWorkflow = class extends BaseResource {
730
+ constructor(options, workflowId) {
731
+ super(options);
732
+ this.workflowId = workflowId;
733
+ }
734
+ /**
735
+ * Creates an async generator that processes a readable stream and yields vNext workflow records
736
+ * separated by the Record Separator character (\x1E)
737
+ *
738
+ * @param stream - The readable stream to process
739
+ * @returns An async generator that yields parsed records
740
+ */
741
+ async *streamProcessor(stream) {
742
+ const reader = stream.getReader();
743
+ let doneReading = false;
744
+ let buffer = "";
745
+ try {
746
+ while (!doneReading) {
747
+ const { done, value } = await reader.read();
748
+ doneReading = done;
749
+ if (done && !value) continue;
750
+ try {
751
+ const decoded = value ? new TextDecoder().decode(value) : "";
752
+ const chunks = (buffer + decoded).split(RECORD_SEPARATOR2);
753
+ buffer = chunks.pop() || "";
754
+ for (const chunk of chunks) {
755
+ if (chunk) {
756
+ if (typeof chunk === "string") {
757
+ try {
758
+ const parsedChunk = JSON.parse(chunk);
759
+ yield parsedChunk;
760
+ } catch {
761
+ }
762
+ }
763
+ }
764
+ }
765
+ } catch {
766
+ }
767
+ }
768
+ if (buffer) {
769
+ try {
770
+ yield JSON.parse(buffer);
771
+ } catch {
772
+ }
773
+ }
774
+ } finally {
775
+ reader.cancel().catch(() => {
776
+ });
777
+ }
778
+ }
779
+ /**
780
+ * Retrieves details about the vNext workflow
781
+ * @returns Promise containing vNext workflow details including steps and graphs
782
+ */
783
+ details() {
784
+ return this.request(`/api/workflows/v-next/${this.workflowId}`);
785
+ }
786
+ /**
787
+ * Retrieves all runs for a vNext workflow
788
+ * @returns Promise containing vNext workflow runs array
789
+ */
790
+ runs() {
791
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
792
+ }
793
+ /**
794
+ * Creates a new vNext workflow run
795
+ * @param params - Optional object containing the optional runId
796
+ * @returns Promise containing the runId of the created run
797
+ */
798
+ createRun(params) {
799
+ const searchParams = new URLSearchParams();
800
+ if (!!params?.runId) {
801
+ searchParams.set("runId", params.runId);
802
+ }
803
+ return this.request(`/api/workflows/v-next/${this.workflowId}/create-run?${searchParams.toString()}`, {
804
+ method: "POST"
805
+ });
806
+ }
807
+ /**
808
+ * Starts a vNext workflow run synchronously without waiting for the workflow to complete
809
+ * @param params - Object containing the runId, inputData and runtimeContext
810
+ * @returns Promise containing success message
811
+ */
812
+ start(params) {
813
+ return this.request(`/api/workflows/v-next/${this.workflowId}/start?runId=${params.runId}`, {
814
+ method: "POST",
815
+ body: { inputData: params?.inputData, runtimeContext: params.runtimeContext }
816
+ });
817
+ }
818
+ /**
819
+ * Resumes a suspended vNext workflow step synchronously without waiting for the vNext workflow to complete
820
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
821
+ * @returns Promise containing success message
822
+ */
823
+ resume({
824
+ step,
825
+ runId,
826
+ resumeData,
827
+ runtimeContext
828
+ }) {
829
+ return this.request(`/api/workflows/v-next/${this.workflowId}/resume?runId=${runId}`, {
830
+ method: "POST",
831
+ stream: true,
832
+ body: {
833
+ step,
834
+ resumeData,
835
+ runtimeContext
836
+ }
837
+ });
838
+ }
839
+ /**
840
+ * Starts a vNext workflow run asynchronously and returns a promise that resolves when the vNext workflow is complete
841
+ * @param params - Object containing the optional runId, inputData and runtimeContext
842
+ * @returns Promise containing the vNext workflow execution results
843
+ */
844
+ startAsync(params) {
845
+ const searchParams = new URLSearchParams();
846
+ if (!!params?.runId) {
847
+ searchParams.set("runId", params.runId);
848
+ }
849
+ return this.request(`/api/workflows/v-next/${this.workflowId}/start-async?${searchParams.toString()}`, {
850
+ method: "POST",
851
+ body: { inputData: params.inputData, runtimeContext: params.runtimeContext }
852
+ });
853
+ }
854
+ /**
855
+ * Resumes a suspended vNext workflow step asynchronously and returns a promise that resolves when the vNext workflow is complete
856
+ * @param params - Object containing the runId, step, resumeData and runtimeContext
857
+ * @returns Promise containing the vNext workflow resume results
858
+ */
859
+ resumeAsync(params) {
860
+ return this.request(`/api/workflows/v-next/${this.workflowId}/resume-async?runId=${params.runId}`, {
861
+ method: "POST",
862
+ body: {
863
+ step: params.step,
864
+ resumeData: params.resumeData,
865
+ runtimeContext: params.runtimeContext
866
+ }
867
+ });
868
+ }
869
+ /**
870
+ * Watches vNext workflow transitions in real-time
871
+ * @param runId - Optional run ID to filter the watch stream
872
+ * @returns AsyncGenerator that yields parsed records from the vNext workflow watch stream
873
+ */
874
+ async watch({ runId }, onRecord) {
875
+ const response = await this.request(`/api/workflows/v-next/${this.workflowId}/watch?runId=${runId}`, {
876
+ stream: true
877
+ });
878
+ if (!response.ok) {
879
+ throw new Error(`Failed to watch vNext workflow: ${response.statusText}`);
880
+ }
881
+ if (!response.body) {
882
+ throw new Error("Response body is null");
883
+ }
884
+ for await (const record of this.streamProcessor(response.body)) {
885
+ onRecord(record);
886
+ }
887
+ }
888
+ };
889
+
551
890
  // src/client.ts
552
891
  var MastraClient = class extends BaseResource {
553
892
  constructor(options) {
@@ -560,6 +899,20 @@ var MastraClient = class extends BaseResource {
560
899
  getAgents() {
561
900
  return this.request("/api/agents");
562
901
  }
902
+ async getAGUI() {
903
+ const agents = await this.request("/api/agents/gui");
904
+ return Object.entries(agents).reduce(
905
+ (acc, [agentId]) => {
906
+ const agent = this.getAgent(agentId);
907
+ acc[agentId] = new AGUIAdapter({
908
+ agentId,
909
+ agent
910
+ });
911
+ return acc;
912
+ },
913
+ {}
914
+ );
915
+ }
563
916
  /**
564
917
  * Gets an agent instance by ID
565
918
  * @param agentId - ID of the agent to retrieve
@@ -640,6 +993,21 @@ var MastraClient = class extends BaseResource {
640
993
  getWorkflow(workflowId) {
641
994
  return new Workflow(this.options, workflowId);
642
995
  }
996
+ /**
997
+ * Retrieves all available vNext workflows
998
+ * @returns Promise containing map of vNext workflow IDs to vNext workflow details
999
+ */
1000
+ getVNextWorkflows() {
1001
+ return this.request("/api/workflows/v-next");
1002
+ }
1003
+ /**
1004
+ * Gets a vNext workflow instance by ID
1005
+ * @param workflowId - ID of the vNext workflow to retrieve
1006
+ * @returns vNext Workflow instance
1007
+ */
1008
+ getVNextWorkflow(workflowId) {
1009
+ return new VNextWorkflow(this.options, workflowId);
1010
+ }
643
1011
  /**
644
1012
  * Gets a vector instance by name
645
1013
  * @param vectorName - Name of the vector to retrieve
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "0.0.0-afterToolExecute-20250414225911",
3
+ "version": "0.0.0-agui-20250501182100",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
6
  "type": "module",
@@ -22,11 +22,16 @@
22
22
  "repository": "github:mastra-ai/client-js",
23
23
  "license": "Elastic-2.0",
24
24
  "dependencies": {
25
+ "@ag-ui/client": "^0.0.27",
25
26
  "@ai-sdk/ui-utils": "^1.1.19",
26
27
  "json-schema": "^0.4.0",
28
+ "rxjs": "7.8.1",
27
29
  "zod": "^3.24.2",
28
30
  "zod-to-json-schema": "^3.24.3",
29
- "@mastra/core": "0.0.0-afterToolExecute-20250414225911"
31
+ "@mastra/core": "0.0.0-agui-20250501182100"
32
+ },
33
+ "peerDependencies": {
34
+ "zod": "^3.24.2"
30
35
  },
31
36
  "devDependencies": {
32
37
  "@babel/preset-env": "^7.26.9",
@@ -36,8 +41,8 @@
36
41
  "@types/node": "^20.17.27",
37
42
  "tsup": "^8.4.0",
38
43
  "typescript": "^5.8.2",
39
- "vitest": "^3.0.9",
40
- "@internal/lint": "0.0.0-afterToolExecute-20250414225911"
44
+ "vitest": "^3.1.2",
45
+ "@internal/lint": "0.0.2"
41
46
  },
42
47
  "scripts": {
43
48
  "build": "tsup src/index.ts --format esm,cjs --dts --clean --treeshake=smallest --splitting",
@@ -0,0 +1,167 @@
1
+ import type { Message } from '@ag-ui/client';
2
+ import { describe, it, expect } from 'vitest';
3
+ import { generateUUID, convertMessagesToMastraMessages } from './agui';
4
+
5
+ describe('generateUUID', () => {
6
+ it('should generate a valid UUID v4 string', () => {
7
+ const uuid = generateUUID();
8
+ // Check UUID format (8-4-4-4-12 hex digits)
9
+ expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
10
+ });
11
+
12
+ it('should generate unique UUIDs', () => {
13
+ const uuids = new Set();
14
+ for (let i = 0; i < 100; i++) {
15
+ uuids.add(generateUUID());
16
+ }
17
+ // All UUIDs should be unique
18
+ expect(uuids.size).toBe(100);
19
+ });
20
+ });
21
+
22
+ describe('convertMessagesToMastraMessages', () => {
23
+ it('should convert user messages correctly', () => {
24
+ const messages: Message[] = [
25
+ {
26
+ id: '1',
27
+ role: 'user',
28
+ content: 'Hello, world!',
29
+ },
30
+ ];
31
+
32
+ const result = convertMessagesToMastraMessages(messages);
33
+
34
+ expect(result).toEqual([
35
+ {
36
+ role: 'user',
37
+ content: 'Hello, world!',
38
+ },
39
+ ]);
40
+ });
41
+
42
+ it('should convert assistant messages correctly', () => {
43
+ const messages: Message[] = [
44
+ {
45
+ id: '1',
46
+ role: 'assistant',
47
+ content: 'Hello, I am an assistant',
48
+ },
49
+ ];
50
+
51
+ const result = convertMessagesToMastraMessages(messages);
52
+
53
+ expect(result).toEqual([
54
+ {
55
+ role: 'assistant',
56
+ content: [{ type: 'text', text: 'Hello, I am an assistant' }],
57
+ },
58
+ ]);
59
+ });
60
+
61
+ it('should convert assistant messages with tool calls correctly', () => {
62
+ const messages: Message[] = [
63
+ {
64
+ id: '1',
65
+ role: 'assistant',
66
+ content: undefined,
67
+ toolCalls: [
68
+ {
69
+ id: 'tool-call-1',
70
+ type: 'function',
71
+ function: {
72
+ name: 'getWeather',
73
+ arguments: '{"location":"San Francisco"}',
74
+ },
75
+ },
76
+ ],
77
+ },
78
+ ];
79
+
80
+ const result = convertMessagesToMastraMessages(messages);
81
+
82
+ expect(result).toEqual([
83
+ {
84
+ role: 'assistant',
85
+ content: [
86
+ {
87
+ type: 'tool-call',
88
+ toolCallId: 'tool-call-1',
89
+ toolName: 'getWeather',
90
+ args: { location: 'San Francisco' },
91
+ },
92
+ ],
93
+ },
94
+ ]);
95
+ });
96
+
97
+ it('should convert tool messages correctly', () => {
98
+ const messages: Message[] = [
99
+ {
100
+ id: '1',
101
+ role: 'tool',
102
+ toolCallId: 'tool-call-1',
103
+ content: '{"temperature":72,"unit":"F"}',
104
+ },
105
+ ];
106
+
107
+ const result = convertMessagesToMastraMessages(messages);
108
+
109
+ expect(result).toEqual([
110
+ {
111
+ role: 'tool',
112
+ content: [
113
+ {
114
+ type: 'tool-result',
115
+ toolCallId: 'tool-call-1',
116
+ toolName: 'unknown',
117
+ result: '{"temperature":72,"unit":"F"}',
118
+ },
119
+ ],
120
+ },
121
+ ]);
122
+ });
123
+
124
+ it('should convert a complex conversation correctly', () => {
125
+ const messages: Message[] = [
126
+ {
127
+ id: '1',
128
+ role: 'user',
129
+ content: "What's the weather in San Francisco?",
130
+ },
131
+ {
132
+ id: '2',
133
+ role: 'assistant',
134
+ content: undefined,
135
+ toolCalls: [
136
+ {
137
+ id: 'tool-call-1',
138
+ type: 'function',
139
+ function: {
140
+ name: 'getWeather',
141
+ arguments: '{"location":"San Francisco"}',
142
+ },
143
+ },
144
+ ],
145
+ },
146
+ {
147
+ id: '3',
148
+ role: 'tool',
149
+ toolCallId: 'tool-call-1',
150
+ content: '{"temperature":72,"unit":"F"}',
151
+ },
152
+ {
153
+ id: '4',
154
+ role: 'assistant',
155
+ content: 'The weather in San Francisco is 72°F.',
156
+ },
157
+ ];
158
+
159
+ const result = convertMessagesToMastraMessages(messages);
160
+
161
+ expect(result).toHaveLength(4);
162
+ expect(result[0].role).toBe('user');
163
+ expect(result[1].role).toBe('assistant');
164
+ expect(result[2].role).toBe('tool');
165
+ expect(result[3].role).toBe('assistant');
166
+ });
167
+ });