@mastra/client-js 0.0.0-pg-pool-options-20250428183821 → 0.0.0-redis-cloud-transporter-20250508191651

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.
@@ -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,3 +1,5 @@
1
+ import type { AbstractAgent } from '@ag-ui/client';
2
+ import { AGUIAdapter } from './adapters/agui';
1
3
  import { Agent, MemoryThread, Tool, Workflow, Vector, BaseResource, Network, VNextWorkflow } from './resources';
2
4
  import type {
3
5
  ClientOptions,
@@ -32,6 +34,25 @@ export class MastraClient extends BaseResource {
32
34
  return this.request('/api/agents');
33
35
  }
34
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
+
35
56
  /**
36
57
  * Gets an agent instance by ID
37
58
  * @param agentId - ID of the agent to retrieve
@@ -180,7 +201,7 @@ export class MastraClient extends BaseResource {
180
201
  * @returns Promise containing telemetry data
181
202
  */
182
203
  public getTelemetry(params?: GetTelemetryParams): Promise<GetTelemetryResponse> {
183
- const { name, scope, page, perPage, attribute } = params || {};
204
+ const { name, scope, page, perPage, attribute, fromDate, toDate } = params || {};
184
205
  const _attribute = attribute ? Object.entries(attribute).map(([key, value]) => `${key}:${value}`) : [];
185
206
 
186
207
  const searchParams = new URLSearchParams();
@@ -205,6 +226,12 @@ export class MastraClient extends BaseResource {
205
226
  searchParams.set('attribute', _attribute);
206
227
  }
207
228
  }
229
+ if (fromDate) {
230
+ searchParams.set('fromDate', fromDate.toISOString());
231
+ }
232
+ if (toDate) {
233
+ searchParams.set('toDate', toDate.toISOString());
234
+ }
208
235
 
209
236
  if (searchParams.size) {
210
237
  return this.request(`/api/telemetry?${searchParams}`);
package/src/index.test.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { MessageType } from '@mastra/core';
2
1
  import { describe, expect, beforeEach, it, vi } from 'vitest';
3
2
 
4
3
  import { MastraClient } from './client';
@@ -489,7 +488,7 @@ describe('MastraClient Resources', () => {
489
488
  const result = await memoryThread.update({
490
489
  title: 'Updated Thread',
491
490
  metadata: { updated: true },
492
- resourceid: 'test-resource',
491
+ resourceId: 'test-resource',
493
492
  });
494
493
  expect(result).toEqual(mockResponse);
495
494
  expect(global.fetch).toHaveBeenCalledWith(
@@ -536,6 +535,7 @@ describe('MastraClient Resources', () => {
536
535
  content: 'test',
537
536
  role: 'user' as const,
538
537
  threadId: 'test-thread',
538
+ resourceId: 'test-resource',
539
539
  createdAt: new Date('2025-03-26T10:40:55.116Z'),
540
540
  },
541
541
  ];
@@ -584,10 +584,10 @@ describe('MastraClient Resources', () => {
584
584
  it('should execute tool', async () => {
585
585
  const mockResponse = { data: 'test' };
586
586
  mockFetchResponse(mockResponse);
587
- const result = await tool.execute({ data: '' });
587
+ const result = await tool.execute({ data: '', runId: 'test-run-id' });
588
588
  expect(result).toEqual(mockResponse);
589
589
  expect(global.fetch).toHaveBeenCalledWith(
590
- `${clientOptions.baseUrl}/api/tools/test-tool/execute`,
590
+ `${clientOptions.baseUrl}/api/tools/test-tool/execute?runId=test-run-id`,
591
591
  expect.objectContaining({
592
592
  method: 'POST',
593
593
  headers: expect.objectContaining({
@@ -1,8 +1,8 @@
1
+ import { processDataStream } from '@ai-sdk/ui-utils';
1
2
  import type { GenerateReturn } from '@mastra/core';
2
3
  import type { JSONSchema7 } from 'json-schema';
3
4
  import { ZodSchema } from 'zod';
4
5
  import { zodToJsonSchema } from 'zod-to-json-schema';
5
- import { processDataStream } from '@ai-sdk/ui-utils';
6
6
 
7
7
  import type {
8
8
  GenerateParams,
@@ -29,7 +29,6 @@ export class AgentTool extends BaseResource {
29
29
  * @param params - Parameters required for tool execution
30
30
  * @returns Promise containing tool execution results
31
31
  */
32
- /** @deprecated use CreateRun/startRun */
33
32
  execute(params: { data: any }): Promise<any> {
34
33
  return this.request(`/api/agents/${this.agentId}/tools/${this.toolId}/execute`, {
35
34
  method: 'POST',
@@ -127,6 +126,7 @@ export class Agent extends BaseResource {
127
126
  params.experimental_output instanceof ZodSchema
128
127
  ? zodToJsonSchema(params.experimental_output)
129
128
  : params.experimental_output,
129
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : undefined,
130
130
  };
131
131
 
132
132
  return this.request(`/api/agents/${this.agentId}/generate`, {
@@ -154,6 +154,7 @@ export class Agent extends BaseResource {
154
154
  params.experimental_output instanceof ZodSchema
155
155
  ? zodToJsonSchema(params.experimental_output)
156
156
  : params.experimental_output,
157
+ runtimeContext: params.runtimeContext ? Object.fromEntries(params.runtimeContext.entries()) : undefined,
157
158
  };
158
159
 
159
160
  const response: Response & {
@@ -1,4 +1,4 @@
1
- import type { RequestFunction, RequestOptions, ClientOptions } from '../types';
1
+ import type { RequestOptions, ClientOptions } from '../types';
2
2
 
3
3
  export class BaseResource {
4
4
  readonly options: ClientOptions;
@@ -1,3 +1,4 @@
1
+ import { processDataStream } from '@ai-sdk/ui-utils';
1
2
  import type { GenerateReturn } from '@mastra/core';
2
3
  import type { JSONSchema7 } from 'json-schema';
3
4
  import { ZodSchema } from 'zod';
@@ -6,7 +7,6 @@ import { zodToJsonSchema } from 'zod-to-json-schema';
6
7
  import type { GenerateParams, ClientOptions, StreamParams, GetNetworkResponse } from '../types';
7
8
 
8
9
  import { BaseResource } from './base';
9
- import { processDataStream } from '@ai-sdk/ui-utils';
10
10
 
11
11
  export class Network extends BaseResource {
12
12
  constructor(
@@ -23,10 +23,16 @@ export class Tool extends BaseResource {
23
23
  * @param params - Parameters required for tool execution
24
24
  * @returns Promise containing the tool execution results
25
25
  */
26
- execute(params: { data: any }): Promise<any> {
27
- return this.request(`/api/tools/${this.toolId}/execute`, {
26
+ execute(params: { data: any; runId?: string }): Promise<any> {
27
+ const url = new URLSearchParams();
28
+
29
+ if (params.runId) {
30
+ url.set('runId', params.runId);
31
+ }
32
+
33
+ return this.request(`/api/tools/${this.toolId}/execute?${url.toString()}`, {
28
34
  method: 'POST',
29
- body: params,
35
+ body: params.data,
30
36
  });
31
37
  }
32
38
  }
@@ -2,6 +2,8 @@ import type { RuntimeContext } from '@mastra/core/runtime-context';
2
2
  import type {
3
3
  ClientOptions,
4
4
  GetVNextWorkflowResponse,
5
+ GetWorkflowRunsParams,
6
+ GetWorkflowRunsResponse,
5
7
  VNextWorkflowRunResult,
6
8
  VNextWorkflowWatchResult,
7
9
  } from '../types';
@@ -67,7 +69,7 @@ export class VNextWorkflow extends BaseResource {
67
69
  }
68
70
  }
69
71
  }
70
- } catch (error) {
72
+ } catch {
71
73
  // Silently ignore parsing errors to maintain stream processing
72
74
  // This allows the stream to continue even if one record is malformed
73
75
  }
@@ -97,6 +99,36 @@ export class VNextWorkflow extends BaseResource {
97
99
  return this.request(`/api/workflows/v-next/${this.workflowId}`);
98
100
  }
99
101
 
102
+ /**
103
+ * Retrieves all runs for a vNext workflow
104
+ * @param params - Parameters for filtering runs
105
+ * @returns Promise containing vNext workflow runs array
106
+ */
107
+ runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse> {
108
+ const searchParams = new URLSearchParams();
109
+ if (params?.fromDate) {
110
+ searchParams.set('fromDate', params.fromDate.toISOString());
111
+ }
112
+ if (params?.toDate) {
113
+ searchParams.set('toDate', params.toDate.toISOString());
114
+ }
115
+ if (params?.limit) {
116
+ searchParams.set('limit', String(params.limit));
117
+ }
118
+ if (params?.offset) {
119
+ searchParams.set('offset', String(params.offset));
120
+ }
121
+ if (params?.resourceId) {
122
+ searchParams.set('resourceId', params.resourceId);
123
+ }
124
+
125
+ if (searchParams.size) {
126
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs?${searchParams}`);
127
+ } else {
128
+ return this.request(`/api/workflows/v-next/${this.workflowId}/runs`);
129
+ }
130
+ }
131
+
100
132
  /**
101
133
  * Creates a new vNext workflow run
102
134
  * @param params - Optional object containing the optional runId
@@ -1,4 +1,10 @@
1
- import type { GetWorkflowResponse, ClientOptions, WorkflowRunResult } from '../types';
1
+ import type {
2
+ GetWorkflowResponse,
3
+ ClientOptions,
4
+ WorkflowRunResult,
5
+ GetWorkflowRunsResponse,
6
+ GetWorkflowRunsParams,
7
+ } from '../types';
2
8
 
3
9
  import { BaseResource } from './base';
4
10
 
@@ -20,6 +26,36 @@ export class Workflow extends BaseResource {
20
26
  return this.request(`/api/workflows/${this.workflowId}`);
21
27
  }
22
28
 
29
+ /**
30
+ * Retrieves all runs for a workflow
31
+ * @param params - Parameters for filtering runs
32
+ * @returns Promise containing workflow runs array
33
+ */
34
+ runs(params?: GetWorkflowRunsParams): Promise<GetWorkflowRunsResponse> {
35
+ const searchParams = new URLSearchParams();
36
+ if (params?.fromDate) {
37
+ searchParams.set('fromDate', params.fromDate.toISOString());
38
+ }
39
+ if (params?.toDate) {
40
+ searchParams.set('toDate', params.toDate.toISOString());
41
+ }
42
+ if (params?.limit) {
43
+ searchParams.set('limit', String(params.limit));
44
+ }
45
+ if (params?.offset) {
46
+ searchParams.set('offset', String(params.offset));
47
+ }
48
+ if (params?.resourceId) {
49
+ searchParams.set('resourceId', params.resourceId);
50
+ }
51
+
52
+ if (searchParams.size) {
53
+ return this.request(`/api/workflows/${this.workflowId}/runs?${searchParams}`);
54
+ } else {
55
+ return this.request(`/api/workflows/${this.workflowId}/runs`);
56
+ }
57
+ }
58
+
23
59
  /**
24
60
  * @deprecated Use `startAsync` instead
25
61
  * Executes the workflow with the provided parameters
@@ -168,7 +204,7 @@ export class Workflow extends BaseResource {
168
204
  }
169
205
  }
170
206
  }
171
- } catch (error) {
207
+ } catch {
172
208
  // Silently ignore parsing errors to maintain stream processing
173
209
  // This allows the stream to continue even if one record is malformed
174
210
  }
package/src/types.ts CHANGED
@@ -8,6 +8,7 @@ import type {
8
8
  StorageThreadType,
9
9
  BaseLogMessage,
10
10
  WorkflowRunResult as CoreWorkflowRunResult,
11
+ WorkflowRuns,
11
12
  } from '@mastra/core';
12
13
 
13
14
  import type { AgentGenerateOptions, AgentStreamOptions } from '@mastra/core/agent';
@@ -55,6 +56,9 @@ export type StreamParams<T extends JSONSchema7 | ZodSchema | undefined = undefin
55
56
 
56
57
  export interface GetEvalsByAgentIdResponse extends GetAgentResponse {
57
58
  evals: any[];
59
+ instructions: string;
60
+ name: string;
61
+ id: string;
58
62
  }
59
63
 
60
64
  export interface GetToolResponse {
@@ -73,6 +77,16 @@ export interface GetWorkflowResponse {
73
77
  workflowId?: string;
74
78
  }
75
79
 
80
+ export interface GetWorkflowRunsParams {
81
+ fromDate?: Date;
82
+ toDate?: Date;
83
+ limit?: number;
84
+ offset?: number;
85
+ resourceId?: string;
86
+ }
87
+
88
+ export type GetWorkflowRunsResponse = WorkflowRuns;
89
+
76
90
  export type WorkflowRunResult = {
77
91
  activePaths: Record<string, { status: string; suspendPayload?: any; stepPath: string[] }>;
78
92
  results: CoreWorkflowRunResult<any, any, any>['results'];
@@ -82,8 +96,17 @@ export type WorkflowRunResult = {
82
96
 
83
97
  export interface GetVNextWorkflowResponse {
84
98
  name: string;
85
- steps: NewWorkflow['steps'];
86
- stepGraph: NewWorkflow['stepGraph'];
99
+ steps: {
100
+ [key: string]: {
101
+ id: string;
102
+ description: string;
103
+ inputSchema: string;
104
+ outputSchema: string;
105
+ resumeSchema: string;
106
+ suspendSchema: string;
107
+ };
108
+ };
109
+ stepGraph: NewWorkflow['serializedStepGraph'];
87
110
  inputSchema: string;
88
111
  outputSchema: string;
89
112
  }
@@ -219,6 +242,8 @@ export interface GetTelemetryParams {
219
242
  page?: number;
220
243
  perPage?: number;
221
244
  attribute?: Record<string, string>;
245
+ fromDate?: Date;
246
+ toDate?: Date;
222
247
  }
223
248
 
224
249
  export interface GetNetworkResponse {