@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/package.json CHANGED
@@ -1,41 +1,52 @@
1
1
  {
2
2
  "name": "@mastra/client-js",
3
- "version": "0.0.0-storage-20250225005900",
3
+ "version": "0.0.0-trigger-playground-ui-package-20250506151043",
4
4
  "description": "The official TypeScript library for the Mastra Client API",
5
5
  "author": "",
6
- "types": "dist/index.d.mts",
7
- "main": "dist/index.mjs",
6
+ "type": "module",
7
+ "types": "dist/index.d.ts",
8
+ "main": "dist/index.js",
8
9
  "exports": {
9
10
  ".": {
10
11
  "import": {
11
- "types": "./dist/index.d.mts",
12
- "default": "./dist/index.mjs"
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
13
18
  }
14
19
  },
15
20
  "./package.json": "./package.json"
16
21
  },
17
22
  "repository": "github:mastra-ai/client-js",
18
- "license": "ISC",
23
+ "license": "Elastic-2.0",
19
24
  "dependencies": {
25
+ "@ag-ui/client": "^0.0.27",
26
+ "@ai-sdk/ui-utils": "^1.1.19",
20
27
  "json-schema": "^0.4.0",
21
- "zod": "^3.24.1",
22
- "zod-to-json-schema": "^3.24.1",
23
- "@mastra/core": "^0.0.0-storage-20250225005900"
28
+ "rxjs": "7.8.1",
29
+ "zod": "^3.24.2",
30
+ "zod-to-json-schema": "^3.24.3",
31
+ "@mastra/core": "0.0.0-trigger-playground-ui-package-20250506151043"
32
+ },
33
+ "peerDependencies": {
34
+ "zod": "^3.24.2"
24
35
  },
25
36
  "devDependencies": {
26
- "@babel/preset-env": "^7.26.0",
27
- "@babel/preset-typescript": "^7.26.0",
28
- "@tsconfig/recommended": "^1.0.7",
37
+ "@babel/preset-env": "^7.26.9",
38
+ "@babel/preset-typescript": "^7.27.0",
39
+ "@tsconfig/recommended": "^1.0.8",
29
40
  "@types/json-schema": "^7.0.15",
30
- "@types/node": "^22.9.0",
31
- "tsup": "^8.0.1",
32
- "typescript": "^5.7.3",
33
- "vitest": "^3.0.4",
34
- "@internal/lint": "0.0.0"
41
+ "@types/node": "^20.17.27",
42
+ "tsup": "^8.4.0",
43
+ "typescript": "^5.8.2",
44
+ "vitest": "^3.1.2",
45
+ "@internal/lint": "0.0.0-trigger-playground-ui-package-20250506151043"
35
46
  },
36
47
  "scripts": {
37
- "build": "tsup-node src/index.ts --format esm --dts --clean --treeshake",
38
- "dev": "tsup-node src/index.ts --format esm --dts --clean --treeshake --watch",
48
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --treeshake=smallest --splitting",
49
+ "dev": "pnpm build --watch",
39
50
  "test": "vitest run"
40
51
  }
41
52
  }
@@ -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
+ });
@@ -0,0 +1,219 @@
1
+ // Cross-platform UUID generation function
2
+ import { AbstractAgent, EventType } from '@ag-ui/client';
3
+ import type {
4
+ BaseEvent,
5
+ RunAgentInput,
6
+ AgentConfig,
7
+ RunStartedEvent,
8
+ RunFinishedEvent,
9
+ TextMessageStartEvent,
10
+ TextMessageContentEvent,
11
+ TextMessageEndEvent,
12
+ Message,
13
+ ToolCallStartEvent,
14
+ ToolCallArgsEvent,
15
+ ToolCallEndEvent,
16
+ } from '@ag-ui/client';
17
+ import type { CoreMessage } from '@mastra/core';
18
+ import { Observable } from 'rxjs';
19
+ import type { Agent } from '../resources/agent';
20
+
21
+ interface MastraAgentConfig extends AgentConfig {
22
+ agent: Agent;
23
+ agentId: string;
24
+ resourceId?: string;
25
+ }
26
+
27
+ export class AGUIAdapter extends AbstractAgent {
28
+ agent: Agent;
29
+ resourceId?: string;
30
+ constructor({ agent, agentId, resourceId, ...rest }: MastraAgentConfig) {
31
+ super({
32
+ agentId,
33
+ ...rest,
34
+ });
35
+ this.agent = agent;
36
+ this.resourceId = resourceId;
37
+ }
38
+
39
+ protected run(input: RunAgentInput): Observable<BaseEvent> {
40
+ return new Observable<BaseEvent>(subscriber => {
41
+ const convertedMessages = convertMessagesToMastraMessages(input.messages);
42
+
43
+ subscriber.next({
44
+ type: EventType.RUN_STARTED,
45
+ threadId: input.threadId,
46
+ runId: input.runId,
47
+ } as RunStartedEvent);
48
+
49
+ this.agent
50
+ .stream({
51
+ threadId: input.threadId,
52
+ resourceId: this.resourceId ?? '',
53
+ runId: input.runId,
54
+ messages: convertedMessages,
55
+ clientTools: input.tools.reduce(
56
+ (acc, tool) => {
57
+ acc[tool.name as string] = {
58
+ id: tool.name,
59
+ description: tool.description,
60
+ inputSchema: tool.parameters,
61
+ };
62
+ return acc;
63
+ },
64
+ {} as Record<string, any>,
65
+ ),
66
+ })
67
+ .then(response => {
68
+ let currentMessageId: string | undefined = undefined;
69
+ return response.processDataStream({
70
+ onTextPart: text => {
71
+ if (currentMessageId === undefined) {
72
+ currentMessageId = generateUUID();
73
+
74
+ const message: TextMessageStartEvent = {
75
+ type: EventType.TEXT_MESSAGE_START,
76
+ messageId: currentMessageId,
77
+ role: 'assistant',
78
+ };
79
+ subscriber.next(message);
80
+ }
81
+
82
+ const message: TextMessageContentEvent = {
83
+ type: EventType.TEXT_MESSAGE_CONTENT,
84
+ messageId: currentMessageId,
85
+ delta: text,
86
+ };
87
+ subscriber.next(message);
88
+ },
89
+ onFinishMessagePart: message => {
90
+ console.log('onFinishMessagePart', message);
91
+ if (currentMessageId !== undefined) {
92
+ const message: TextMessageEndEvent = {
93
+ type: EventType.TEXT_MESSAGE_END,
94
+ messageId: currentMessageId,
95
+ };
96
+ subscriber.next(message);
97
+ }
98
+ // Emit run finished event
99
+ subscriber.next({
100
+ type: EventType.RUN_FINISHED,
101
+ threadId: input.threadId,
102
+ runId: input.runId,
103
+ } as RunFinishedEvent);
104
+
105
+ // Complete the observable
106
+ subscriber.complete();
107
+ },
108
+ onToolCallPart(streamPart) {
109
+ const parentMessageId = currentMessageId || generateUUID();
110
+ subscriber.next({
111
+ type: EventType.TOOL_CALL_START,
112
+ toolCallId: streamPart.toolCallId,
113
+ toolCallName: streamPart.toolName,
114
+ parentMessageId,
115
+ } as ToolCallStartEvent);
116
+
117
+ subscriber.next({
118
+ type: EventType.TOOL_CALL_ARGS,
119
+ toolCallId: streamPart.toolCallId,
120
+ delta: JSON.stringify(streamPart.args),
121
+ parentMessageId,
122
+ } as ToolCallArgsEvent);
123
+
124
+ subscriber.next({
125
+ type: EventType.TOOL_CALL_END,
126
+ toolCallId: streamPart.toolCallId,
127
+ parentMessageId,
128
+ } as ToolCallEndEvent);
129
+ },
130
+ });
131
+ })
132
+ .catch(error => {
133
+ console.log('error', error);
134
+ // Handle error
135
+ subscriber.error(error);
136
+ });
137
+
138
+ return () => {};
139
+ });
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Generates a UUID v4 that works in both browser and Node.js environments
145
+ */
146
+ export function generateUUID(): string {
147
+ // Use crypto.randomUUID() if available (Node.js environment or modern browsers)
148
+ if (typeof crypto !== 'undefined') {
149
+ // Browser crypto API or Node.js crypto global
150
+ if (typeof crypto.randomUUID === 'function') {
151
+ return crypto.randomUUID();
152
+ }
153
+ // Fallback for older browsers
154
+ if (typeof crypto.getRandomValues === 'function') {
155
+ const buffer = new Uint8Array(16);
156
+ crypto.getRandomValues(buffer);
157
+ // Set version (4) and variant (8, 9, A, or B)
158
+ buffer[6] = (buffer[6]! & 0x0f) | 0x40; // version 4
159
+ buffer[8] = (buffer[8]! & 0x3f) | 0x80; // variant
160
+
161
+ // Convert to hex string in UUID format
162
+ let hex = '';
163
+ for (let i = 0; i < 16; i++) {
164
+ hex += buffer[i]!.toString(16).padStart(2, '0');
165
+ // Add hyphens at standard positions
166
+ if (i === 3 || i === 5 || i === 7 || i === 9) hex += '-';
167
+ }
168
+ return hex;
169
+ }
170
+ }
171
+
172
+ // Last resort fallback (less secure but works everywhere)
173
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
174
+ const r = (Math.random() * 16) | 0;
175
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
176
+ return v.toString(16);
177
+ });
178
+ }
179
+
180
+ export function convertMessagesToMastraMessages(messages: Message[]): CoreMessage[] {
181
+ const result: CoreMessage[] = [];
182
+
183
+ for (const message of messages) {
184
+ if (message.role === 'assistant') {
185
+ const parts: any[] = message.content ? [{ type: 'text', text: message.content }] : [];
186
+ for (const toolCall of message.toolCalls ?? []) {
187
+ parts.push({
188
+ type: 'tool-call',
189
+ toolCallId: toolCall.id,
190
+ toolName: toolCall.function.name,
191
+ args: JSON.parse(toolCall.function.arguments),
192
+ });
193
+ }
194
+ result.push({
195
+ role: 'assistant',
196
+ content: parts,
197
+ });
198
+ } else if (message.role === 'user') {
199
+ result.push({
200
+ role: 'user',
201
+ content: message.content || '',
202
+ });
203
+ } else if (message.role === 'tool') {
204
+ result.push({
205
+ role: 'tool',
206
+ content: [
207
+ {
208
+ type: 'tool-result',
209
+ toolCallId: message.toolCallId,
210
+ toolName: 'unknown',
211
+ result: message.content,
212
+ },
213
+ ],
214
+ });
215
+ }
216
+ }
217
+
218
+ return result;
219
+ }
package/src/client.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { Agent, MemoryThread, Tool, Workflow, Vector, BaseResource } from './resources';
1
+ import type { AbstractAgent } from '@ag-ui/client';
2
+ import { AGUIAdapter } from './adapters/agui';
3
+ import { Agent, MemoryThread, Tool, Workflow, Vector, BaseResource, Network, VNextWorkflow } from './resources';
2
4
  import type {
3
5
  ClientOptions,
4
6
  CreateMemoryThreadParams,
@@ -9,11 +11,12 @@ import type {
9
11
  GetLogsResponse,
10
12
  GetMemoryThreadParams,
11
13
  GetMemoryThreadResponse,
14
+ GetNetworkResponse,
12
15
  GetTelemetryParams,
13
16
  GetTelemetryResponse,
14
17
  GetToolResponse,
18
+ GetVNextWorkflowResponse,
15
19
  GetWorkflowResponse,
16
- RequestOptions,
17
20
  SaveMessageToMemoryParams,
18
21
  SaveMessageToMemoryResponse,
19
22
  } from './types';
@@ -31,6 +34,25 @@ export class MastraClient extends BaseResource {
31
34
  return this.request('/api/agents');
32
35
  }
33
36
 
37
+ public async getAGUI({ resourceId }: { resourceId: string }): Promise<Record<string, AbstractAgent>> {
38
+ const agents = await this.getAgents();
39
+
40
+ return Object.entries(agents).reduce(
41
+ (acc, [agentId]) => {
42
+ const agent = this.getAgent(agentId);
43
+
44
+ acc[agentId] = new AGUIAdapter({
45
+ agentId,
46
+ agent,
47
+ resourceId,
48
+ });
49
+
50
+ return acc;
51
+ },
52
+ {} as Record<string, AbstractAgent>,
53
+ );
54
+ }
55
+
34
56
  /**
35
57
  * Gets an agent instance by ID
36
58
  * @param agentId - ID of the agent to retrieve
@@ -121,6 +143,23 @@ export class MastraClient extends BaseResource {
121
143
  return new Workflow(this.options, workflowId);
122
144
  }
123
145
 
146
+ /**
147
+ * Retrieves all available vNext workflows
148
+ * @returns Promise containing map of vNext workflow IDs to vNext workflow details
149
+ */
150
+ public getVNextWorkflows(): Promise<Record<string, GetVNextWorkflowResponse>> {
151
+ return this.request('/api/workflows/v-next');
152
+ }
153
+
154
+ /**
155
+ * Gets a vNext workflow instance by ID
156
+ * @param workflowId - ID of the vNext workflow to retrieve
157
+ * @returns vNext Workflow instance
158
+ */
159
+ public getVNextWorkflow(workflowId: string) {
160
+ return new VNextWorkflow(this.options, workflowId);
161
+ }
162
+
124
163
  /**
125
164
  * Gets a vector instance by name
126
165
  * @param vectorName - Name of the vector to retrieve
@@ -162,17 +201,9 @@ export class MastraClient extends BaseResource {
162
201
  * @returns Promise containing telemetry data
163
202
  */
164
203
  public getTelemetry(params?: GetTelemetryParams): Promise<GetTelemetryResponse> {
165
- const { name, scope, page, perPage, attribute } = params || {};
204
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
166
205
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
167
206
 
168
- const queryObj = {
169
- ...(name ? { name } : {}),
170
- ...(scope ? { scope } : {}),
171
- ...(page ? { page: String(page) } : {}),
172
- ...(perPage ? { perPage: String(perPage) } : {}),
173
- ...(_attribute?.length ? { attribute: _attribute } : {}),
174
- } as const;
175
-
176
207
  const searchParams = new URLSearchParams();
177
208
  if (name) {
178
209
  searchParams.set('name', name);
@@ -195,6 +226,12 @@ export class MastraClient extends BaseResource {
195
226
  searchParams.set('attribute', _attribute);
196
227
  }
197
228
  }
229
+ if (fromDate) {
230
+ searchParams.set('fromDate', fromDate.toISOString());
231
+ }
232
+ if (toDate) {
233
+ searchParams.set('toDate', toDate.toISOString());
234
+ }
198
235
 
199
236
  if (searchParams.size) {
200
237
  return this.request(`/api/telemetry?${searchParams}`);
@@ -202,4 +239,21 @@ export class MastraClient extends BaseResource {
202
239
  return this.request(`/api/telemetry`);
203
240
  }
204
241
  }
242
+
243
+ /**
244
+ * Retrieves all available networks
245
+ * @returns Promise containing map of network IDs to network details
246
+ */
247
+ public getNetworks(): Promise<Record<string, GetNetworkResponse>> {
248
+ return this.request('/api/networks');
249
+ }
250
+
251
+ /**
252
+ * Gets a network instance by ID
253
+ * @param networkId - ID of the network to retrieve
254
+ * @returns Network instance
255
+ */
256
+ public getNetwork(networkId: string) {
257
+ return new Network(this.options, networkId);
258
+ }
205
259
  }
package/src/example.ts CHANGED
@@ -1,43 +1,65 @@
1
- import { MastraClient } from './client';
2
-
3
- (async () => {
4
- const client = new MastraClient({
5
- baseUrl: 'http://localhost:4111',
6
- });
7
-
8
- try {
9
- const agent = client.getAgent('weatherAgent');
10
- const response = await agent.stream({
11
- messages: [
12
- {
13
- role: 'user',
14
- content: 'Hello, world!',
15
- },
16
- ],
17
- });
18
-
19
- const reader = response?.body?.getReader();
20
- const decoder = new TextDecoder();
21
- let buffer = '';
22
-
23
- while (true) {
24
- if (!reader) break;
25
- const { value, done } = await reader.read();
26
- if (done) break;
27
-
28
- const chunk = decoder.decode(value);
29
- buffer += chunk;
30
-
31
- console.log(buffer);
32
-
33
- const matches = buffer.matchAll(/0:"([^"]*)"/g);
34
-
35
- for (const match of matches) {
36
- const content = match[1];
37
- process.stdout.write(`${content}\n`);
38
- }
39
- }
40
- } catch (error) {
41
- console.error(error);
42
- }
43
- })();
1
+ // import { MastraClient } from './client';
2
+ // import type { WorkflowRunResult } from './types';
3
+
4
+ // Agent
5
+
6
+ // (async () => {
7
+ // const client = new MastraClient({
8
+ // baseUrl: 'http://localhost:4111',
9
+ // });
10
+
11
+ // console.log('Starting agent...');
12
+
13
+ // try {
14
+ // const agent = client.getAgent('weatherAgent');
15
+ // const response = await agent.stream({
16
+ // messages: 'what is the weather in new york?',
17
+ // })
18
+
19
+ // response.processDataStream({
20
+ // onTextPart: (text) => {
21
+ // process.stdout.write(text);
22
+ // },
23
+ // onFilePart: (file) => {
24
+ // console.log(file);
25
+ // },
26
+ // onDataPart: (data) => {
27
+ // console.log(data);
28
+ // },
29
+ // onErrorPart: (error) => {
30
+ // console.error(error);
31
+ // },
32
+ // });
33
+
34
+ // } catch (error) {
35
+ // console.error(error);
36
+ // }
37
+ // })();
38
+
39
+ // Workflow
40
+ // (async () => {
41
+ // const client = new MastraClient({
42
+ // baseUrl: 'http://localhost:4111',
43
+ // });
44
+
45
+ // try {
46
+ // const workflowId = 'myWorkflow';
47
+ // const workflow = client.getWorkflow(workflowId);
48
+
49
+ // const { runId } = await workflow.createRun();
50
+
51
+ // workflow.watch({ runId }, record => {
52
+ // console.log(new Date().toTimeString(), record);
53
+ // });
54
+
55
+ // await workflow.start({
56
+ // runId,
57
+ // triggerData: {
58
+ // city: 'New York',
59
+ // },
60
+ // });
61
+
62
+ // } catch (e) {
63
+ // console.error('Workflow error:', e);
64
+ // }
65
+ // })();